source: anagram/trunk/anagram.hs @ 8

Last change on this file since 8 was 2, checked in by simon, 19 years ago

A little anagram thingie got imported here.

File size: 1.1 KB
Line 
1-- anagram.hs: Program to find the anagrams of a word in a word list
2
3import Char
4import System
5import IO
6
7-- Remove one occurrence of an element from a list
8deleteOne e [] = []
9deleteOne e (y:ys)
10    | e == y    = ys
11    | otherwise = y : deleteOne e ys
12
13-- Test if the strings is an re-arrangements of each other
14anagram []     [] = True
15anagram []     ys = False
16anagram xs     [] = False
17anagram (x:xs) ys = elem x ys && anagram xs (deleteOne x ys)
18
19printStrList = putStr . concat . map (++ "\n")
20
21main = do
22    args <- getArgs
23    case args of
24        [string,file]  -> do
25            chars <- readFile file
26            printStrList (filter (anagram string') (phrases chars))
27                where string'   = filter isAlpha string
28                      phrases c = map (filter isAlpha) (lines c)
29        [string]    -> do
30            chars <- getContents
31            printStrList (filter (anagram string) (lines chars))
32        _           -> do
33            putStr "Usage: "
34            getProgName >>= putStr
35            putStrLn " WORD [FILE]"
36            putStrLn "List anagrams of WORD from FILE or standard input."
37            exitWith (ExitFailure 1)
38
Note: See TracBrowser for help on using the repository browser.