Other functional programming languages have this feature, such as OCaml:
match x with
| Some n when n < 10 -> ...
| Some n when n < 100 -> ...
...
or Haskell:
case x of
Just n | n < 10 -> ...
| n < 100 -> ...
...
Why was it removed from Elm? (Earlier versions apparently had it.)
What is the idiomatic way to express the same in Elm?
Use an if
expression. That's really all guards are anyway:
case x of
_ ->
if x > 10 then
...
else
...
In some cases this does result in duplicate else
branches that could otherwise have been covered by a single _
branch. The solution to this is the same as for code reuse anywhere else though: Use functions:
let
default = ...
in
case x of
Some y ->
if y > 10 then
...
else
default
_ ->
default
(Note that default
here will be strictly evaluated. If the computation is expensive, add ()
as a dummy argument to evaluate it lazily.)
Why was it removed? Well, I can't read Evan's mind any more that you can, but my guess is because it complicates both the syntax and semantics of case
expressions.
For example, a common mistake for beginners is to get confused when the compiler complains that a case
expression isn't exhaustive when they've provided branches with guards that do cover all the cases:
case x of
_ | x < 10 -> ...
_ | x >= 10 -> ...
-- Error: This `case` does not have branches for all possibilities
-- Why u do dis, compiler?
The mix of static patterns with exhaustiveness checking and dynamic guard expressions that can use variables and operators is very confusing to many beginners. Many also use case
expressions with guards instead of any if
expression, just because case
"feels more functional".
Not having guards therefore makes for a language that is much easier to learn and still just as capable, at the cost of being slightly more verbose in some relatively rare cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With