User:Duplode/Apfelmus' loop for Control structures

From Wikibooks, open books for an open world
Jump to navigation Jump to search


There are legitimate uses of return () as a placeholder do-nothing action. For instance, take the following action:

loop = do
    c <- getChar
    if c == 'Q' 
        then return ()
        else loop
    putStrLn ""
    putStrLn [c]

Admittedly, this looks a lot like a while (true) / break loop in your favourite imperative language. As we can tell now, however, there is something quite different going on here.

Explain, step by step, what the loop action in the final box note does, and in particular what is the role of the return (). Hints:

  • getChar is an action analogous to getLine, except that, instead of taking a newline-terminated series of characters from the standard input and making a IO String, it takes just a single character as soon as it is input.
  • If you have trouble with the control flow within loop, run it in GHCi to get a better feel of what it does.