{- ---------------------------------------- Some (better!) examples of IO and monadic computation, for CS 454, Spring 2005 ---------------------------------------- -} module IODemo where -------------------- -- a very simple echo, in 2 different notations echo = do input <- getLine putStrLn input echq = do { input <- getLine ; putStrLn input } -- or on two lines echo' = getLine >>= putStrLn str = "this is a very long, loong, \ \long, long string" -------------------- -- a better exchange: prompt, response & report exch p r = do putStr (p++"? ") line <- getLine putStrLn (r ++ ": " ++ line) exch' p r = putStr (p++"? ") >> getLine >>= putStrLn . ((r++": ") ++) io = exch "eh" "oh" -------------------- -- prompt & response in different languages prompts = [ "Input", "Eingang", "Entrada" ] reports = [ "You said", "Sie sagten", "Usted dijo" ] -- a list of instantiated exchanges -- (i.e., a list of *computations*) dialog = [ exch p r | p<-prompts, r<-reports ] -- ee: English / English -- gs: German / Spanish ee = dialog !! 0 gs = dialog !! 5 -------------------- -- a "for loop" over computations (processes) for 0 c = return () for n c = do { c ; for (n-1) c } -- forever c = c >> return (forever c) -- forever c = do { c ; forever c } -- forever c = do c -- forever c -- a list of iterated dialogs (3 times each) dialog3 = map (for 3) dialog -------------------- -- an exchange with "memory" of the response -- (this is easier to write in "do" notation) exchn p r = do putStr (p++"? ") input <- getLine let output = r ++ ": " ++ input putStrLn output return input -- a "while loop" predicated on responses while p c = do y <- c if p y then while p c else putStrLn "Done." tilBlank = while (not . null) dialog' = [ tilBlank (exchn p r) | p<-prompts, r<-reports ] -- doing without the "do" cond p x y z = if p z then x else y while' p c = c >>= cond p (while' p c) (return ()) -------------------- -- non-computational monads (list) lm1 = do { n <- [1..10] ; c <- "abc" ; return (replicate n c) } lm2 = do { c <- "abc" ; n <- [1..10] ; return (replicate n c) }