OCaml Pattern match with non-constants

后端 未结 3 692
天命终不由人
天命终不由人 2021-01-20 00:02

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\"
|         


        
3条回答
  •  心在旅途
    2021-01-20 00:29

    You need when guard:

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

    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.

    Note that matching a constant (match 2 with) is not a good idea.

提交回复
热议问题