Reputation: 171321
Javascript's switch
supports a fallthrough:
function update(action, model) {
switch (action) {
case SHUFFLE:
return shuffle(model);
case MOVE_LEFT:
case MOVE_RIGHT:
case MOVE_UP:
case MOVE_DOWN:
return move(action, model);
default:
return model;
}
}
How would you implement this in Elm?
Upvotes: 3
Views: 1491
Reputation: 2923
I would model it like this:
type Direction = Left | Right | Up | Down
type Action = Shuffle | Move Direction
update action model =
case action of
Shuffle -> shuffle model
Move dir -> move dir model
Elm's case does not have fall-through.
"a case-expression does not have fall through, so you don't need to say break everywhere to make things sane."
http://elm-lang.org/guide/model-the-problem
Upvotes: 7
Reputation: 6366
I think pdamoc's answer is the best for what you're trying to do. However, in the interest of completeness, no Elm cases do not support fallthrough. The best solution is to extract the common code into a function. If you model your data well, you can reduce the number of different cases that call this function.
Case expressions support default using _ -> code
, which should always be the last case, since it will match anything. You should avoid using this if you can; in 0.16 the compiler will detect unhandled cases for you.
Finally, you can use if
and equality on union tags, but it's generally worse than using case
.
if List.member action [MoveLeft, MoveRight, MoveUp, MoveDown]
then move action model
else shuffle model
Upvotes: 4