Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why were case guards removed from Elm?

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?

like image 512
ᅙᄉᅙ Avatar asked Dec 01 '19 08:12

ᅙᄉᅙ


1 Answers

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.

like image 74
glennsl Avatar answered Oct 13 '22 17:10

glennsl