How can you access the last element in a list in ocaml
Solution 1
No, there's no pattern that matches against the end of a list. It's not an attractive structure in OCaml because it takes linear time to find the end of a list. OCaml pattern matching is supposed to be fast.
You can reverse your list and match the beginning of the reversed list. It's only a constant factor slower than finding the end of a list.
Solution 2
If you want to get the last element then you can traverse the list recursively until you encounter this case: | [x] -> x
Solution 3
As the other answers says, you have to traverse/reverse the list to access it.
Depending on the specific problem, you could consider to use another data structure.
OCaml's standard library provides Queue
, which could be of interest to you:
http://caml.inria.fr/pub/docs/manual-ocaml/libref/Queue.html
James Notaro
Updated on June 04, 2022Comments
-
James Notaro almost 2 years
I know that when using ocaml pattern matching it is possible to use
h::t
When using this the h with refer to the first element in a list and the t will refer to the rest of the list. Is it possible to use this same type of matching to get the last element in a list. So the t will refer to the last element and the h will refer to the rest of the list.An example of code that this would be useful for is
let rec remove x y = match y with [] -> x | h::t -> remove (remove_element x (get_last y)) h ;;
-
James Notaro about 9 yearsThat worked perfectly I even had a reverse function already created. Thank you
-
Sam Olesen about 9 yearsA reverse function already exists in the standard library:
List.rev