Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

last element in list using ocaml List.fold_left

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!

like image 486
meta_warrior Avatar asked Sep 09 '13 13:09

meta_warrior


1 Answers

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"
like image 83
nlucaroni Avatar answered Oct 06 '22 00:10

nlucaroni