|
|
|
# Pattern Guards
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
**Ticket:** [\#56](https://gitlab.haskell.org//haskell/prime/issues/56)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
See [ExtensionDescriptionHowto](extension-description-howto) for information on how to write these extension descriptions. Please add any new extensions to the list of [HaskellExtensions](haskell-extensions).
|
|
|
|
|
|
|
|
|
|
|
|
## Brief Explanation
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The syntax for guards is changed to
|
|
|
|
|
|
|
|
|
|
|
|
>
|
|
|
|
>
|
|
|
|
> *gd* → `|` *qual*<sub>1</sub>`,` …`,` *qual*<sub>n</sub>
|
|
|
|
>
|
|
|
|
>
|
|
|
|
|
|
|
|
|
|
|
|
(Haskell 98 allows only a single, Boolean, guard.)
|
|
|
|
In pattern guards of the form *p* `<-` *e*, the two sides must have the same type, and if the value if *e* does not match *p*, the guards fails.
|
|
|
|
|
|
|
|
|
|
|
|
## References
|
|
|
|
|
|
|
|
|
|
|
|
- [ Case Expressions](http://www.haskell.org/onlinereport/exps.html#case) and [ Formal Semantics of Pattern Matching](http://www.haskell.org/onlinereport/exps.html#case-semantics) in the Haskell 98 Report
|
|
|
|
- [ Simon's original proposal](http://research.microsoft.com/~simonpj/Haskell/guards.html), 1997.
|
|
|
|
- [ Pattern guards](http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#pattern-guards) in the GHC User's Guide
|
|
|
|
- [ Pattern Guards and Transformational Patterns](http://research.microsoft.com/Users/simonpj/Papers/pat.htm), Martin Erwig and Simon Peyton Jones, Haskell Workshop, 2000.
|
|
|
|
|
|
|
|
## Pros
|
|
|
|
|
|
|
|
|
|
|
|
- avoids awkward `case` constructs in certain situations
|
|
|
|
- a relatively small and orthogonal extension
|
|
|
|
- the required changes to the Report are clearly laid out in the above paper.
|
|
|
|
|
|
|
|
## Cons
|
|
|
|
|
|
|
|
|
|
|
|
- the re-use of monadic binding notation from list comprehensions and `do`-notation for pure matching is confusing, but the more rational `=` would create parsing difficulties, e.g.
|
|
|
|
|
|
|
|
```wiki
|
|
|
|
f p | x = y = z
|
|
|
|
```
|
|
|
|
|
|
|
|
## Results of committee discussion for Haskell 2010
|
|
|
|
|
|
|
|
|
|
|
|
- in the first bullet in 3.13, there's a double period, and I don't
|
|
|
|
think the contextual difference can be called "minor".
|
|
|
|
|
|
|
|
- it would help to present the three types of guard in the same order
|
|
|
|
each time they're discussed.
|
|
|
|
|
|
|
|
- in 3.17, the rule for clause (w) has parentheses around p ← e0,
|
|
|
|
which is not permitted by the syntax. |