Pattern matching a variable in OCaml?

假装没事ソ 提交于 2020-01-03 18:33:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!