OCaml模式与非常量匹配 [英] OCaml Pattern match with non-constants
问题描述
是否可以对变量而不是常量值进行模式匹配:
Is it possible to do pattern matching on variables instead of constant values:
# let x = 2 in
let y = 5 in
match 2 with
| x -> "foo"
| y -> "bar"
| _ -> "baz";;
let y = 5 in
Warning 26: unused variable y.
let x = 2 in
Warning 26: unused variable x.
| y -> "bar"
Warning 11: this match case is unused.
| _ -> "baz";;
Warning 11: this match case is unused.
- : string = "foo"
很显然,使用这种语法,x -> "foo"
情况包含所有内容.有没有办法使其等同于:
Obviously, with this syntax, the x -> "foo"
case takes everything. Is there a way to make it be equivalent to:
match 2 with
| 2 -> "foo"
| 5 -> "bar"
| _ -> "baz"
匹配表达式的值是在运行时确定的?
where the values of the match expressions are determined at runtime?
推荐答案
您需要when
保护:
let x = 2 in
let y = 5 in
match 2 with
| z when z = x -> "foo"
| z when z = y -> "bar"
| _ -> "baz";;
错误消息很有启发性.使用时:
The error messages are very instructive. When you use:
let x = 2 in
...
match 2 with
| x -> "foo"
| ...
新值x
在上一个让步边界中遮盖了值x
,因此是第一条错误消息.此外,由于新的x
匹配所有内容,因此y
和_
的以下两个模式显然是多余的.
the new value x
shadows the value x
in previous let-bound hence the first error message. Moreover, since the new x
matches everything, two below patterns of y
and _
are obviously redundant.
请注意,匹配常数(match 2 with
)并不是一个好主意.
Note that matching a constant (match 2 with
) is not a good idea.
这篇关于OCaml模式与非常量匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!