last element in list using ocaml List.fold_left

好久不见. 提交于 2019-12-23 09:17:12

问题


I can find the last element of a list by the following code.

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

How do I find the last element of the same list using the List.fold_left function in OCaml? Thanks in advance!


回答1:


fold_left accesses the list from the head to the tail, thus the function passed to fold_left should just replace the accumulator with the current element of the list. Thus simply,

let last = function
  | x::xs -> List.fold_left (fun _ y -> y) x xs
  | []    -> failwith "no element"

You can write your function directly, without the aux function.

let rec last = function
  | x::[] -> x
  | _::xs -> last xs
  | []    -> failwith "no element"


来源:https://stackoverflow.com/questions/18699256/last-element-in-list-using-ocaml-list-fold-left

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!