Module Stdlib320.List

A module containing basic list operations

Basic functions

val length : 'a list -> int

length l is the number of elements in l

let _ = assert (length [1;2;3] = 3)
val nth : 'a list -> int -> 'a

nth l i is the ith element of l if i >= 0 and i < length l

let _ = assert (nth [1;2;3] 1 = 2)

Raises a Failure exception if length l < i and an Invalid_argument exception if i < 0

val nth_opt : 'a list -> int -> 'a option

Same as the previous function, but is None in the case of failure.

val rev : 'a list -> 'a list

Reverses a list

let _ = assert ([rev [1;2;3] = [3;2;1]])
val concat : 'a list list -> 'a list

Combines a list of lists from left to right

let _ = assert ([concat [[1;2;3];[4;5;6];[7;8;9]] = [1;2;3;4;5;6;7;8;9]])

Higher-order functions

val map : ('a -> 'b) -> 'a list -> 'b list

map f l is l but with f applied to every element

let _ = assert (map abs [-1;-2;-3] = [1;2;3])
val filter : ('a -> bool) -> 'a list -> 'a list

filter f l is the elements of l (in order) which satisfy the predicate f

let _ = assert ([filter ((<) 5) [3;4;5;6;7] = [6;7]])
val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a list -> 'acc

Left-associative folding function for lists. fold_left op init [x_1;x_2;...;x_n] is equivalent to op (...(op (op init x_1) x_2)...) x_n

val fold_right : ('a -> 'acc -> 'acc) -> 'a list -> 'acc -> 'acc

Right-associative folding function for lists. fold_right op [x_1;x_2;...;x_n] is equivalent to op x_1 (op x_2 (...(op x_n base)...))

Finding

val mem : 'a -> 'a list -> bool

Membership predicate for lists. mem x l is

  • true if x appears in l
  • false otherwise
val find : ('a -> bool) -> 'a list -> 'a

Finds based on a predicate. find f l is the first appearance of an element of l which satisfies f.

Raises a Not_found exception otherwise.

val find_opt : ('a -> bool) -> 'a list -> 'a option

Same as the previous function, but is None in the case of failure.

Sorting

val sort : ('a -> 'a -> int) -> 'a list -> 'a list

Generic sorting function for lists. sort f l has the same elements as l, but sorted according to the comparing function f

Association lists

val assoc : 'a -> ('a * 'b) list -> 'b

Membership function for association lists. assoc x l is equivalent to

snd (find (fun (k, v) -> k = x))

val assoc_opt : 'a -> ('a * 'b) list -> 'b option

Same as the previous function, but is None in the case of failure

val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list

remove_assoc k l is l but with the first appearance of a pair of the form (k, v) removed

Printers

val sprint : ('a -> string) -> 'a list -> string
val print : ('a -> string) -> 'a list -> unit