-------------------- -- Simple examples of interaction -- -- from the Prelude, -- interact :: (String -> String) -> IO () echo = interact id stut = interact (concatMap (replicate 3)) uhoh = interact reverse -- can't reverse until we've seen the end! -------------------- -- Using getLine to see input string *as* a string check = getLine >>= print check' = do { line <- getLine; print line } -------------------- -- Line-by-line user interaction bylines g = unlines . g . lines tilEmpty = takeWhile (not . null) interline f = interact (bylines (map f . tilEmpty)) interecho f = interact (bylines (map (join f) . tilEmpty)) join f s = s ++ "\n" ++ f s -------------------- -- A fuller user interaction utility demo title f = do putStrLn ("\nWelcome to the " ++ title) putStrLn "(one input per line, to quit)\n" interline (prompt f) putStrLn ("\nThanks for trying the " ++ title) where prompt f x = concat ["\t> ",x,"\n\t",f x] -------------------- -- Another user interaction utility (more imperative) demo' title f = do putStrLn ("\nWelcome to the " ++ title) putStrLn "(one input per line, to quit)\n" repPrompt f putStrLn ("\nThanks for trying the " ++ title) where repPrompt f = do putStr "\t> " input <- getLine if not (null input) then do -- putStrLn (indent input) putStrLn (indent (f input)) repPrompt f else return () indent = ("\t"++) -------------------- -- Interaction example: palindrome checker normalize = map toLower . filter isAlpha palindrome s = (n == reverse n) where n = normalize s adam = "Madam, in Eden, I'm Adam." canal = "A man, a plan, a canal ... Panama!" paldemo = demo "palindrome checker" (show . palindrome) -------------------- -- Interaction example: ROT-13 rot13 = map (\c -> if isAlpha c then shift c else c) shift c = chr (ord c + if toLower c < 'n' then 13 else -13) rotdemo = demo' "ROT-13 translator" rot13