how to get the value of the last element of a List? I\'ve noted that List.hd (or .Head) return an item, while List.tl (or .Tail) returns a List.
Is rev the List and
Try this function. It uses recursion, though it gets optimised to iteration anyway since it's tail recursion. In any case, it is most likely quicker than reversing the entire list (using List.rev
).
let rec last = function
| hd :: [] -> hd
| hd :: tl -> last tl
| _ -> failwith "Empty list."
The answer of Pavel Minaev is definitely worth taking into account, however. Nonetheless, the algorithm you have requested may be useful in some rare cases, and is the most efficient way to go about the task.
A more concise version based on Mitch's answer:
let lastItem = myList |> List.rev |> List.head
The myList
list is sent to List.rev
function. The result is then processed by List.head
A quick & dirty way of doing it is by using List.reduce. Assuming the list is called ls
,
let lastElement ls = List.reduce (fun _ i -> i) ls
As for efficiency, I agree with Pavel.
I think you can just write
list.[0..list.Length-1]
Agreed, not so efficient to get the last element of list
, or any other "enumerable" sequence. That said, this function already exists in the Seq
module, Seq.last
.
Below code worked fine with me, I've an array of integers, want to start from the 5th item, then take it minus the item number
Sum of [Array(xi) - Array(xi-5)] where i start at 5
The code used is:
series |> Array.windowed 5
|> Array.fold (fun s x ->
(x |> Array.rev |> Array.head) - (x |> Array.head) + s) 0
|> float