OCaml中模式匹配中的名称绑定



在本练习中,名称与as-关键字绑定的作用是什么:https://ocaml.org/problems#17

# let split list n =
let rec aux i acc = function
| [] -> List.rev acc, []
| h :: t as l -> if i = 0 then List.rev acc, l
else aux (i - 1) (h :: acc) t 
in
aux n [] list;;

它是否允许我们在if/else子句中选择在函数模式匹配中使用尾部t还是列表l?函数式编程中名称绑定的常见用途是什么?非常感谢。

as关键字允许您将名称绑定到模式的较大和较小部分。在您提供的示例中:

let split list n =
let rec aux i acc = function
| [] -> List.rev acc, []
| h::t as l -> if i = 0 then List.rev acc, l
else aux (i - 1) (h :: acc) t 
in
aux n [] list

l绑定到整个列表,h绑定到列表的头部,t绑定到尾部。

如果没有as,您可能会写:

let split list n =
let rec aux i acc = function
| [] -> List.rev acc, []
| h::t -> if i = 0 then List.rev acc, (h::t)
else aux (i - 1) (h :: acc) t 
in
aux n [] list

请记住,CCD_;贪婪的;左边,可能需要括号来消除优先级的歧义。

例如

h::h'::t as lst

整个列表绑定到lst

如果你想绑定尾部,还需要列表中的第二个元素:

h::(h'::_ as tl)

最新更新