"case .. of" 是否支持 Elm 中的 fallthrough?
Does "case .. of" supports a fallthrough in Elm?
Javascript 的 switch
支持 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;
}
}
你会如何在 Elm 中实现它?
我会这样建模:
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 的案例没有失败。
"a case-expression does not have fall through, so you don't need to say break everywhere to make things sane."
我认为 pdamoc 的答案最适合您的尝试。但是,为了完整起见,没有 Elm 案例不支持 fallthrough。最好的解决方案是将公共代码提取到一个函数中。如果你很好地建模你的数据,你可以减少调用这个函数的不同案例的数量。
Case 表达式支持默认使用 _ -> code
,这应该始终是最后一个案例,因为它将匹配任何内容。如果可以的话,你应该避免使用它;在 0.16 中,编译器将为您检测未处理的情况。
最后,你可以在 union 标签上使用 if
和相等性,但它通常比使用 case
更糟糕。
if List.member action [MoveLeft, MoveRight, MoveUp, MoveDown]
then move action model
else shuffle model
Javascript 的 switch
支持 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;
}
}
你会如何在 Elm 中实现它?
我会这样建模:
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 的案例没有失败。
"a case-expression does not have fall through, so you don't need to say break everywhere to make things sane."
我认为 pdamoc 的答案最适合您的尝试。但是,为了完整起见,没有 Elm 案例不支持 fallthrough。最好的解决方案是将公共代码提取到一个函数中。如果你很好地建模你的数据,你可以减少调用这个函数的不同案例的数量。
Case 表达式支持默认使用 _ -> code
,这应该始终是最后一个案例,因为它将匹配任何内容。如果可以的话,你应该避免使用它;在 0.16 中,编译器将为您检测未处理的情况。
最后,你可以在 union 标签上使用 if
和相等性,但它通常比使用 case
更糟糕。
if List.member action [MoveLeft, MoveRight, MoveUp, MoveDown]
then move action model
else shuffle model