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

17,105

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

Share:
17,105
James Notaro
Author by

James Notaro

Updated on June 04, 2022

Comments

  • James Notaro
    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
    James Notaro about 9 years
    That worked perfectly I even had a reverse function already created. Thank you
  • Sam Olesen
    Sam Olesen about 9 years
    A reverse function already exists in the standard library: List.rev