我可以通过以下代码找到列表的最后一个元素。
let last (xs:'a list) : 'a =
let rec aux xs prev =
match xs with
| [] -> prev
| x::ys -> aux ys x in
match xs with
| [] -> failwith "no element"
| x::xs -> aux xs x
如何使用OCaml中的List.fold_left
函数找到同一列表的最后一个元素?
提前谢谢!
答案 0 :(得分:4)
fold_left
从头到尾访问列表,因此传递给fold_left
的函数应该只用列表的当前元素替换累加器。因此,简单地说,
let last = function
| x::xs -> List.fold_left (fun _ y -> y) x xs
| [] -> failwith "no element"
您可以直接编写函数,而无需aux
函数。
let rec last = function
| x::[] -> x
| _::xs -> last xs
| [] -> failwith "no element"