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
;;
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] ).
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.
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.
If you want to get the last element then you can traverse the list recursively until you encounter this case: | [x] -> x
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