CSCE 314 Lecture 19

From Notes
Jump to navigation Jump to search

« previous | Monday, October 10, 2011 | next »


Composing Monads

sequence :: [M a] -> M [a]
sequence [] = return []
sequence (c:cs) = c >>= \x ->
    sequence cs >>= \xs ->
    return (x:xs)

-- usage
labels :: [String]
labels = ["Name: ", "Gender: ", "Nationality: "]

prompts :: [IO String]
prompts = map (\s -> putStr s >> getLine) labels

test1a :: IO [()]
test1a = sequence_ prompts

test1b :: IO [()]
test1b =
    let printAnswer x = putStrLn ("  Your answer was: " ++ x)
        prompts' = map (>>= printAnswer) prompts
    in sequence_ prompts'