OCaml Pattern match with non-constants

后端 未结 3 690
天命终不由人
天命终不由人 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:42

    A "when" guard is what you're looking for here:

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

    ...though I'm not sure why you'd ever want to match with a constant.

提交回复
热议问题