如何在匹配中添加条件以防...
How to add a condition to a match in case ... of
在函数式语言中,可以将条件添加到模式匹配的分支中:例如,在 OCaml 中:
let value = match something with
| OneThing -> "1"
| Another when condition -> "2"
| _ -> "3"
如何在榆树中做到这一点?我尝试了 when
和 if
,但没有任何效果。
Elm 在模式匹配中没有条件,可能是因为语言设计者倾向于保持语法小而简单。
你能做的最好的事情是这样的:
let
value =
case something of
OneThing ->
"1"
Another ->
if condition then
"2"
else
...
_ ->
"3"
作为在 case
分支中使用 if
的替代方法,您可能想要匹配包含条件的元组,如下所示:
let
value =
case ( something, condition ) of
( OneThing, _ ) ->
"1"
( Another, True ) ->
"2"
_ ->
"3"
在函数式语言中,可以将条件添加到模式匹配的分支中:例如,在 OCaml 中:
let value = match something with
| OneThing -> "1"
| Another when condition -> "2"
| _ -> "3"
如何在榆树中做到这一点?我尝试了 when
和 if
,但没有任何效果。
Elm 在模式匹配中没有条件,可能是因为语言设计者倾向于保持语法小而简单。
你能做的最好的事情是这样的:
let
value =
case something of
OneThing ->
"1"
Another ->
if condition then
"2"
else
...
_ ->
"3"
作为在 case
分支中使用 if
的替代方法,您可能想要匹配包含条件的元组,如下所示:
let
value =
case ( something, condition ) of
( OneThing, _ ) ->
"1"
( Another, True ) ->
"2"
_ ->
"3"