问题
If I do
let check n = function
| n -> true
| _ -> false
then I get Warning 11: this match case is unused.
I understand why, since the n
in | n -> true is actually not the argument of check
. It is basically a variable created by the pattern matching.
My question is, in this case, do we have any way to still using pattern matching (instead of if else) to force this check?
I.e., I want to pattern match with the argument n
.
回答1:
You can use when
to have patterns along with boolean conditions:
let check n = function
| x when x = n -> true
| _ -> false
However, this isn't very special: it's just different syntax for using an if
.
OCaml does not support any sort of "dynamic" pattern that lets you match against the value of a variable--patterns are all static. There is a research language called bondi which does support dynamic patterns like this. It's quite similar to OCaml, so if you're interested in this sort of feature you should play around with it.
回答2:
You get that warning because n
matches the same (any value) as _
, hence you can never reach the second match case. Which hins to possible problems in your program.
来源:https://stackoverflow.com/questions/17674549/pattern-matching-a-variable-in-ocaml