Chapter 3. Monads

Monads are for carrying around state implicitly...

3.1. The IO monad

Any function which performs input or output must be in the IO monad. Below are two functions, isPalin and main. The former is not in the IO monad, it takes a String and returns a Bool, whereas main is in the IO monad, it has no input and returns an empty IO action.

isPalin :: String -> Bool
isPalin s = s == (reverse s)

main :: IO ()
main = do putStr "Give me a word and I'll  tell you if its a palindrome: "
	  ourLine <- getLine
	  if isPalin ourLine
	     then putStr (ourLine ++ " is indeed a palindrom.\n")
	     else putStr (ourLine ++ " is not a palindrom.\n")

Things to note:

  1. Functions, like main, which perform IO must have the IO monad in their type signatures.

  2. A function that is not in the IO monad cannot call a function that is in the IO monad, so you can think of this IO type as "tainting" anything it touches.

  3. For now, IO actions must be inside a do statement.