Previous Contents Next
19.16 Module List: list operations


Some functions are flagged as not tail-recursive. A tail-recursive function uses constant stack space, while a non-tail-recursive function uses stack space proportional to the length of its list argument, which can be a problem with very long lists. When the function takes several list arguments, an approximate formula giving stack usage (in some unspecified constant unit) is shown in parentheses.

The above considerations can usually be ignored if your lists are not longer than about 10000 elements.
val length : 'a list -> int
Return the length (number of elements) of the given list.
val hd : 'a list -> 'a
Return the first element of the given list. Raise Failure "hd" if the list is empty.
val tl : 'a list -> 'a list
Return the given list without its first element. Raise Failure "tl" if the list is empty.
val nth : 'a list -> int -> 'a
Return the n-th element of the given list. The first element (head of the list) is at position 0. Raise Failure "nth" if the list is too short.
val rev : 'a list -> 'a list
List reversal.
val append : 'a list -> 'a list -> 'a list
Catenate two lists. Same function as the infix operator @. Not tail-recursive (length of the first argument). The @ operator is not tail-recursive either.
val rev_append : 'a list -> 'a list -> 'a list
List.rev_append l1 l2 reverses l1 and catenates it to l2. This is equivalent to List.rev l1 @ l2, but rev_append is tail-recursive and more efficient.
val concat  : 'a list list -> 'a list
val flatten : 'a list list -> 'a list
Catenate (flatten) a list of lists. Not tail-recursive (length of the argument + length of the longest sub-list).
Iterators
val iter : ('a -> unit) -> 'a list -> unit
List.iter f [a1; ...; an] applies function f in turn to a1; ...; an. It is equivalent to begin f a1; f a2; ...; f an; () end.
val map : ('a -> 'b) -> 'a list -> 'b list
List.map f [a1; ...; an] applies function f to a1, ..., an, and builds the list [f a1; ...; f an] with the results returned by f. Not t