简体   繁体   中英

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
;;

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.

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

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

I can find 2 patterns that match the last element of a list, one mentioned already by aycc. This is for quick testing:

# let matchtest = function
   | []         -> "empty list"
   | [x]        ->  "single element list with " ^ x
   | x :: []    -> "last element: " ^ x
   | x :: tail  -> "at least 2 elements"
  ;;
Warning 11: this match case is unused.
val matchtest : string list -> string = <fun>

The warning is for the line returning "last element...", making evident that [x] and x :: [] are the same.

So when traversing the list recursively you can identify the last element. But you can't have the first and the last element in one pattern.

One alternative approach would be to convert the list to array with Array.of_list , there you find the last element at index (Array.length yourarray) - 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM