Match OCaml patterns with non-constants

Is it possible to match patterns by 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"

Obviously, with this syntax, case x -> "foo"takes everything. Is there a way to make this equivalent:

match 2 with
| 2 -> "foo"
| 5 -> "bar"
| _ -> "baz"

where are the values โ€‹โ€‹of matching expressions determined at runtime?

+3
source share
3 answers

You need a whenguard:

let x = 2 in
let y = 5 in
match 2 with
| z when z = x -> "foo"
| z when z = y -> "bar"
| _ -> "baz";;

Error messages are very instructive. When you use:

let x = 2 in
...
match 2 with
| x -> "foo"
| ...

the new value xobscures the value xin the previous let-bound, hence the first error message. Moreover, since the new one xmatches everyone, the two are lower than the template yand _clearly redundant.

, (match 2 with) .

+5

A when - , . , , . , , ", | y -> .. , ", .

, . , when , (, , , ..). .

if ... then .. else if .. then .. else.

if z = x then "foo"
else if z = y then "bar"
else "baz"

when? , , ( ..) , . if..then..else.

, , ( ):

match foo with
| (Baz x) when pred x -> ...
| _ -> ... 
+6

A ", " - , :

let x = 2 in
let y = 5 in
match 2 with
| x' when x' = x -> "foo"
| y' when y' = y -> "baz"
| _ -> "baz" ;;

... , - .

+3
source

All Articles