Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you access the last element in a list in ocaml

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
;;
like image 933
James Notaro Avatar asked Mar 24 '15 23:03

James Notaro


People also ask

What does :: do in OCaml?

Regarding the :: symbol - as already mentioned, it is used to create lists from a single element and a list ( 1::[2;3] creates a list [1;2;3] ).

Can you index a list in OCaml?

You cannot have O(1) indexing of linked lists. You must linearly traverse them. However, OCaml does have arrays, which are fixed-size containers with O(1) indexing.

What does list ITER do OCaml?

List. iter just returns () , which is a specifically uninteresting value. I.e., List. iter is for when you just want to call a function that doesn't return anything interesting.


Video Answer


1 Answers

If you want to get the last element then you can traverse the list recursively until you encounter this case: | [x] -> x

like image 61
aycc Avatar answered Nov 16 '22 17:11

aycc