在Haskell中,在模式匹配时,我可以使用@
来获取模式中的整个结构。 (为了便于谷歌搜索,这种结构称为as-pattern。)
例如,x:xs
将列表分解为头部和尾部;我也可以使用xxs@(x:xs)
获取整个列表。
OCaml有这样的东西吗?
答案 0 :(得分:18)
您可以使用as
:
let f = function
| [] -> (* ... *)
| (x::xs) as l ->
(*
here:
- x is the head
- xs is the tail
- l is the whole list
*)
答案 1 :(得分:13)
让我用一些例子来扩展艾蒂安的答案:
let x :: xs as list = [1;2;3];;
val x : int = 1
val xs : int list = [2; 3]
val list : int list = [1; 2; 3]
当您编写<pattern> as <name>
时,变量<name>
绑定到左侧的整个模式,换句话说,as
的范围尽可能向左延伸(更具技术性as
的优先级低于构造函数,即构造函数绑定更紧密。因此,在深度模式匹配的情况下,您可能需要使用括号来限制范围,例如,
let [x;y] as fst :: ([z] as snd) :: xs as list = [[1;2];[3]; [4]];;
val x : int = 1
val y : int = 2
val fst : int list = [1; 2]
val z : int = 3
val snd : int list = [3]
val xs : int list list = [[4]]
val list : int list list = [[1; 2]; [3]; [4]]