Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of the last element of a list

Tags:

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 get the hd the only way around? Thanks.

like image 673
pistacchio Avatar asked Jul 23 '09 23:07

pistacchio


People also ask

How do I find the last value in a list?

Get the last item of a list using list. To get the last element of the list using list. pop(), the list. pop() method is used to access the last element of the list.

What is the last index of a list element?

Method 1: Using negative indexing This means that the last value in a sequence has an index of −1, the second last has an index of −2, and so on.

How do you slice the last element of a list in Python?

Another efficient, yet simple approach to delete the last element of the list is by using the del statement. The del operator deletes the element at the specified index location from the list. To delete the last element, we can use the negative index -1.


1 Answers

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.

like image 198
Noldorin Avatar answered Sep 20 '22 16:09

Noldorin