是否有可能做模式匹配的變量,而不是常量:OCaml的模式匹配與非常量
# 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"
顯然,這種語法中,x -> "foo"
情況發生的一切。有沒有辦法讓它等同於:
match 2 with
| 2 -> "foo"
| 5 -> "bar"
| _ -> "baz"
其中匹配表達式的值是在運行時確定的嗎?
是啊,我知道,常量匹配是不是一個好主意。這僅僅是爲了舉例。 –
我認爲在這裏使用'when'守衛是一個壞主意,並且往往會在程序員(特別是初學者)中造成不好的風格。 – gasche