|
|
# The `do`-notation and `if`-`then`-`else`
|
|
|
# Conditionals and `do`-notation
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
This page concerns the possibility of tweaking the layout rules to avoid a common pitfall when `if`-`then`-`else` is used with the `do`-notation.
|
|
|
It only documents a problem: no specific solution is proposed. The issue is somewhat related to [NondecreasingIndentation](nondecreasing-indentation).
|
|
|
Strictly speaking, the issue is not tied to the `do`-notation, but that is where it (almost?) always shows up.
|
|
|
|
|
|
|
|
|
## Brief Explanation
|
|
|
|
|
|
|
... | ... | @@ -34,42 +28,41 @@ put beginners off. |
|
|
|
|
|
|
|
|
|
|
|
Might it be possible to handle `then` and `else` specially to avoid this problem? At least in the context of `do`?
|
|
|
Or might it be possible to treat `if` as something that opens a kind of explicit layout context (which would
|
|
|
prevent the insertion of a closing `}`) that is closed by a matching `else`?
|
|
|
Strictly speaking, the issue is not tied to the `do`-notation, but that is where it (almost?) always shows up.
|
|
|
|
|
|
|
|
|
## Implementation
|
|
|
## Proposal
|
|
|
|
|
|
|
|
|
|
|
|
This has been implemented in jhc by changing a single line in the parser, an equivalant change in the report should have the same effect.
|
|
|
Change the syntax for conditionals to
|
|
|
|
|
|
|
|
|
```wiki
|
|
|
old:
|
|
|
| 'if' exp 'then' exp 'else' exp { HsIf $2 $4 $6 }
|
|
|
new:
|
|
|
| 'if' exp optsemi 'then' exp optsemi 'else' exp { HsIf $2 $5 $8 }
|
|
|
```
|
|
|
>
|
|
|
>
|
|
|
> exp → `if` exp<sub>1</sub> \[`;`\] `then` exp<sub>2</sub> \[`;`\] `else` exp<sub>3</sub>
|
|
|
>
|
|
|
>
|
|
|
|
|
|
|
|
|
i.e., add optional semicolons before `then` and `else`, making the above example legal.
|
|
|
This has been recently added to jhc and GHC, and
|
|
|
so far, it has not caused any problems.
|
|
|
|
|
|
|
|
|
## References
|
|
|
|
|
|
|
|
|
- [ Conditionals](http://www.haskell.org/onlinereport/exps.html#conditionals) in the Haskell 98 Report
|
|
|
- Somewhat related to [NondecreasingIndentation](nondecreasing-indentation)
|
|
|
|
|
|
## Pros
|
|
|
|
|
|
|
|
|
- Would address a layout issue that manifestly trips up a lot of people and which at least one
|
|
|
experienced Haskell programmer (me!) finds very annoying.
|
|
|
- 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
|
|
|
|
|
|
|
|
|
- No concrete proposal yet
|
|
|
- Not implemented in any system to my knowledge |