Open main menu

Wikibooks β


< Haskell‎ | Solutions

Explicit characters in place of indentationEdit


Rewrite this snippet from the Control Structures chapter using explicit braces and semicolons:

doGuessing num = do
  putStrLn "Enter your guess:"
  guess <- getLine
  case compare (read guess) num of
    LT -> do putStrLn "Too low!"
             doGuessing num
    GT -> do putStrLn "Too high!"
             doGuessing num
    EQ -> putStrLn "You Win!"

There are of course many valid answers, given that you can indent the code and break the lines however you wish. Here is one of them:

doGuessing num = do {
  putStrLn "Enter your guess:";
  guess <- getLine;
  case compare (read guess) num of {
    LT -> do {
      putStrLn "Too low!";
      doGuessing num;
    GT -> do {
      putStrLn "Too high!";
      doGuessing num;
    EQ -> putStrLn "You Win!";

Layout in actionEdit

The if-within-do problem has tripped up so many Haskellers, that one programmer has posted a proposal to the Haskell prime initiative to add optional semicolons between if then else. How would that fix the problem?

Then {if expr; then code; else other_code}, or

if expr
then code
else other_code

becomes legal.