6

我可以通过以下代码找到列表的最后一个元素。

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

如何使用List.fold_leftOCaml 中的函数找到同一列表的最后一个元素?提前致谢!

4

1 回答 1

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"
于 2013-09-09T13:49:54.733 回答