Pattern matching a variable in OCaml?

ocaml, pattern-matching

Solution

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.

Problem

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`.

Original source