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!
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With