【问题标题】:last element in list using ocaml List.fold_left使用 ocaml List.fold_left 的列表中的最后一个元素
【发布时间】:2013-09-13 00:03:33
【问题描述】:

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

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 函数找到同一列表的最后一个元素? 提前致谢!

【问题讨论】:

    标签: list functional-programming ocaml


    【解决方案1】:

    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"
    

    【讨论】:

      猜你喜欢
      • 2012-12-31
      • 1970-01-01
      • 2010-12-06
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      • 2012-09-29
      • 2015-01-13
      • 2011-05-31
      相关资源
      最近更新 更多