wiki:DoAndIfThenElse

Version 11 (modified by malcolm.wallace@…, 7 years ago) (diff)

--

Conditionals and do-notation

Brief Explanation

I have lost count of how many times people (including very experienced programmers) have approached me wondering why on earth code like the following fails to parse:

foo :: Monad m => Bool -> m Int
foo x = do
    if x then
        return 1
    else
        return 2

When I explain that they have to indent the else at least one more step, they invariably stare at me in disbelief and vow to henceforth stay far away from languages where layout has semantic significance. It can actually be somewhat embarassing, and it certainly can put beginners off.

Strictly speaking, the issue is not tied to the do-notation, but that is where it (almost?) always shows up.

Jon Fairbairn suggests that case should get the same treatment, for consistency:

do case whatever
   of
      blah -> bluh
      blah' -> bluh'

or perhaps

do case whatever of
   Cons -> bluh
   Nil  -> foo

Proposal

Change the syntax for conditionals to

exp -> if exp1 [;] then exp2 [;] else exp3

i.e., add optional semicolons before then and else, making the above example legal. This has been recently added to jhc, GHC and Hugs, and so far it has not caused any problems.

The second optional semicolon is the important one. The first one just adds a little more convenience; it has been suggested that it would be consistent to do the same before of in case expressions.

Possible addition: optional semicolon before/(after?) of in case expressions too.

References

Tickets

#23
DoAndIfThenElse

Pros

  • Would address a layout issue that manifestly trips up a lot of people, and many experienced Haskell programmers find very annoying.
  • Trivial to implement
  • Independent of the layout rule.

Cons

  • It has been pointed out that improved error reporting could alleviate this issue to some extent, without any language change. An alternative might thus be to add a section to the report with recommendations concerning "best practices" for reporting errors related to this issue and other that are known to cause confusion.