BatList
Additional and modified functions for lists.
The OCaml standard library provides a module for list functions. This BatList module can be used to extend the List module or as a standalone module. It provides new functions and modify the behavior of some other ones (in particular all functions are now tail-recursive).
The following functions have the same behavior as the List
module ones but are tail-recursive: map
, append
, concat
, flatten
, fold_right
, remove_assoc
, remove_assq
, split
. That means they will not cause a Stack_overflow
when used on very long list.
The implementation might be a little more slow in bytecode, but compiling in native code will not affect performances.
This module extends Stdlib's List module, go there for documentation on the rest of the functions and types.
List operations.
@documents List
The type of lists
include BatEnum.Enumerable with type 'a enumerable = 'a t
type 'a enumerable = 'a t
The data structure, e.g. 'a List.t
include BatInterfaces.Mappable with type 'a mappable = 'a t
type 'a mappable = 'a t
The data structure, e.g. 'a List.t
Compare the lengths of two lists. compare_lengths l1 l2
is equivalent to compare (length l1) (length l2)
, except that the computation stops after itering on the shortest list.
Compare the length of a list to an integer. compare_length_with l n
is equivalent to compare (length l) n
, except that the computation stops after at most n
iterations on the list.
at_opt
returns the n-th element of the list l
or None if the index is beyond the length of l
.
val shuffle : ?state:Random.State.t -> 'a list -> 'a list
shuffle ~state:rs l
randomly shuffles the elements of l
. The optional random state rs
allows to control the random numbers being used during shuffling (for reproducibility).
Shuffling is implemented using the Fisher-Yates algorithm on an array and works in O(n), where n is the number of elements of l
.
append l1 l2
is a concatenation of l1
and l2
. Same function as the infix operator @
. Tail-recursive. This function takes O(length l1
) time.
List.rev_append l1 l2
reverses l1
and concatenates it to l2
.
Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Tail-recursive.
Similar to String.make
, make n x
returns a list containing n
elements x
.
range 1 `To 3
= [1; 2; 3]
. range 3 `Downto 1
= [3; 2; 1]
.
frange start `To stop n
generates (without accumulating floating point errors) n
floats in the range [start..stop]
. n
must be >= 2. At each step, floats in an increasing (resp. decreasing) range increase (resp. decrease) by approximately (stop - start) / (n - 1).
Similar to Array.init
, init n f
returns the list containing the results of (f 0),(f 1).... (f (n-1)).
unfold init f
creates a list by repeatedly applying f
to the second element of its own result, starting from the initial value init
. The first element of each result is accumulated in a list. The list is terminated and returned as soon as f
returns None
.
Example: List.unfold 0 (fun x -> if x = 3 then None else Some (string_of_int x, x+1))
will return ["0";"1";"2"]
Creates a list containing the results of sequential calls to f()
. f()
is called repeatedly until it throws an exception. Both the results list, as well as the exception thrown are returned in a (results_list, exn)
pair. Warning: if calls to f()
never throw an exception, unfold_exn is an infinite loop.
equal eq [a1; ...; an] [b1; ..; bm]
holds when the two input lists have the same length, and for each pair of elements ai
, bi
at the same position we have eq ai bi
.
Note: the eq
function may be called even if the lists have different length. If you know your equality function is costly, you may want to check compare_lengths
first.
List.iter f [a0; a1; ...; an]
applies function f
in turn to a0; a1; ...; an
. It is equivalent to begin f a0; f a1; ...; f an; () end
.
iteri f l
will call (f 0 a0); (f 1 a1) ... (f n an)
where a0..an
are the elements of the list l
.
map f [a0; a1; ...; an]
applies function f
to a0, a1, ..., an
, and builds the list [f a0; f a1; ...; f an]
with the results returned by f
. Tail-recursive.
List.rev_map f l
gives the same result as List
.rev (
List
.map f l)
.
mapi f l
will build the list containing (f 0 a0); (f 1 a1) ... (f n an)
where a0..an
are the elements of the list l
.
List.fold_left f a [b0; b1; ...; bn]
is f (... (f (f a b0) b1) ...) bn
.
As fold_left
, but with the index of the element, from 0
to length li - 1
, as additional argument.
List.fold_right f [a0; a1; ...; an] b
is f a0 (f a1 (... (f an b) ...))
. Tail-recursive.
As fold_right
, but with the index of the element, from 0
to length li - 1
, as additional argument.
Combines fold_left
and map
. Tail-recursive.
More precisely :
fold_left_map f acc [] = (acc, [])
fold_left_map f acc (x :: xs) =
let (acc', y) = f acc x in
let (res, ys) = fold_left_map acc' xs in
(res, y :: ys)
sum l
returns the sum of the integers of l
. Returns 0
on the empty list. Note: prior to 2.11.0, used to raise Invalid_argument on the empty list.
fsum l
returns the sum of the floats of l
. Returns 0.
on the empty list. Note: prior to 2.11.0, used to raise Invalid_argument on the empty list.
kahan_sum l
returns a numerically-accurate sum of the floats of l
. See BatArray.fsum
for more details.
min_max l
returns the pair (smallest, largest) from l
as judged by Pervasives.compare
(by default). You can provide another comparison function via the optional cmp
parameter.
val to_seq : 'a list -> 'a Seq.t
Iterate on the list
val of_seq : 'a Seq.t -> 'a list
Create a list from the iterator
List.iter2 f [a0; a1; ...; an] [b0; b1; ...; bn]
calls in turn f a0 b0; f a1 b1; ...; f an bn
.
List.iter2i f [a0; a1; ...; an] [b0; b1; ...; bn]
calls in turn f 0 a0 b0; f 1 a1 b1; ...; f n an bn
.
List.map2 f [a0; a1; ...; an] [b0; b1; ...; bn]
is [f a0 b0; f a1 b1; ...; f an bn]
.
List.map2i f [a0; a1; ...; an] [b0; b1; ...; bn]
is [f 0 a0 b0; f 1 a1 b1; ...; f n an bn]
.
List.rev_map2 f l1 l2
gives the same result as List
.rev (
List
.map2 f l1 l2)
, but is tail-recursive and more efficient.
List.fold_left2 f a [b0; b1; ...; bn] [c0; c1; ...; cn]
is f (... (f (f a b0 c0) b1 c1) ...) bn cn
.
List.fold_right2 f [a0; a1; ...; an] [b0; b1; ...; bn] c
is f a0 b0 (f a1 b1 (... (f an bn c) ...))
.
Same as List
.mem, but the comparator function is explicitly provided.
Same as List
.mem, but uses physical equality instead of structural equality to compare list elements.
for_all p [a0; a1; ...; an]
checks if all elements of the list satisfy the predicate p
. That is, it returns (p a0) && (p a1) && ... && (p an)
.
exists p [a0; a1; ...; an]
checks if at least one element of the list satisfies the predicate p
. That is, it returns (p a0) || (p a1) || ... || (p an)
.
Same as List
.for_all, but for a two-argument predicate.
Same as List
.exists, but for a two-argument predicate.
subset cmp l l'
check if all elements of the list l
is contained in the list l'
by applying cmp
as comparator.
find p l
returns the first element of the list l
that satisfies the predicate p
.
find_opt p l
returns the first element of the list l
that satisfies the predicate p
, or None
if there is no value that satisfies p
in the list l
.
find_map_opt f l
applies f
to the elements of l
in order, and returns the first result of the form Some v
, or None
if none exist.
find_exn p e l
returns the first element of l
such as p x
returns true
or raises e
if such an element has not been found.
findi p l
returns the first element ai
of l
along with its index i
such that p i ai
is true, or
find_map pred list
finds the first element of list
for which pred element
returns Some r
. It returns r
immediately once found or
List.concat_map f l
gives the same result as List
.concat (
List
.map f l)
. Tail-recursive.
rfind p l
returns the last element x
of l
such as p x
returns true
or
filter p l
returns all the elements of the list l
that satisfy the predicate p
. The order of the elements in the input list is preserved.
count_matching p l
returns the number of elements in l
that satisfy p
. Semantically equivalent but faster than length (filter p l)
.
filteri p [a0; a1; ...; an]
returns all the elements ai
of index i
that satisfy the predicate p i ai
. The order of the elements in the input list is preserved.
filter_map f l
calls (f a0) (f a1).... (f an)
where a0,a1..an
are the elements of l
. It returns the list of elements bi
such as f ai = Some bi
(when f
returns None
, the corresponding element of l
is discarded).
filteri_map f l
calls (f 0 a0) (f 1 a1).... (f n an)
where a0,a1..an
are the elements of l
. It returns the list of elements bi
such as f ai = Some bi
(when f
returns None
, the corresponding element of l
is discarded).
partition p l
returns a pair of lists (l1, l2)
, where l1
is the list of all the elements of l
that satisfy the predicate p
, and l2
is the list of all the elements of l
that do not satisfy p
. The order of the elements in the input list is preserved.
val partition_map : ('a -> ('b, 'c) BatEither.t) -> 'a list -> 'b list * 'c list
partition_map f l
returns a pair of lists (l1, l2)
such that, for each element x
of the input list l
:
f x
is Left y1
, then y1
is in l1
, andf x
is Right y2
, then y2
is in l2
. The output elements are included in l1
and l2
in the same relative order as the corresponding input elements in l
. In particular, partition_map (fun x -> if f x then Left x else Right x) l
is equivalent to partition f l
.index_of e l
returns the index of the first occurrence of e
in l
, or None
if there is no occurrence of e
in l
index_ofq e l
behaves as index_of e l
except it uses physical equality
rindex_of e l
returns the index of the last occurrence of e
in l
, or None
if there is no occurrence of e
in l
rindex_ofq e l
behaves as rindex_of e l
except it uses physical equality
unique cmp l
returns the list l
without any duplicate element. The default comparator ( = ) is used if no comparison function specified.
Implementation Note: The current implementation removes any elements where the tail of the list contains an equal element, thus it keeps the *last* copy of each equal element.
This function takes O(n^2) time.
As unique
, except comparator parameter returns an int. Default comparator is Pervasives.compare
. This function takes O(n log n) time.
Implementation Note: The current implementation removes subsequent elements that compare as equal to earlier elements in the list, thus it keeps the *first* copy of each equal element.
As unique
, except uses a hash table to cut down the expected runtime to linear, assuming a good hash function. ?hash
defaults to Hashtbl.hash
and ?eq
defaults to (=)
.
Implementation Note: The current implementation removes subsequent elements that hash and compare as equal to earlier elements in the list, thus it keeps the *first* copy of each equal element.
assoc a l
returns the value associated with key a
in the list of pairs l
. That is, assoc a [ ...; (a,b); ...] = b
if (a,b)
is the leftmost binding of a
in list l
.
assoc_opt a l
returns the value associated with key a
in the list of pairs l
. That is, assoc_opt a [ ...; (a,b); ...] = b
if (a,b)
is the leftmost binding of a
in list l
. Returns None
if there is no value associated with a
in the list l
.
assoc_inv b l
returns the key associated with value b
in the list of pairs l
. That is, assoc b [ ...; (a,b); ...] = a
if (a,b)
is the leftmost binding of a
in list l
.
remove_assoc a l
returns the list of pairs l
without the first pair with key a
, if any. Tail-recursive.
Same as List
.assoc, but simply return true if a binding exists, and false if no bindings exist for the given key.
Same as List
.assoc, but uses physical equality instead of structural equality to compare keys.
Same as List
.assoc_opt, but uses physical equality instead of structural equality to compare keys.
Same as List
.assoc_inv, but uses physical equality instead of structural equality to compare keys.
Same as List
.remove_assoc, but uses physical equality instead of structural equality to compare keys. Tail-recursive.
Same as List
.mem_assoc, but uses physical equality instead of structural equality to compare keys.
modify a f l
returns the same list as l
but with value associated to key a
replaced with f a
.
modify_def dfl a f l
performs as modify a f l
except that it add an association from a
to f dfl
instead of raising Not_found
.
modify_opt a f l
allows to modify the binding for a
in l
or absence thereof.
modify_at n f l
returns the same list as l
but with nth-value a
replaced with f a
.
modify_opt_at n f l
returns the same list as l
but with nth-value a
removed if f a
is None
, and replaced by v
if it is Some v
.
split_at n l
returns two lists l1
and l2
, l1
containing the first n
elements of l
and l2
the others.
remove l x
returns the list l
without the first element x
found or returns l
if no element is equal to x
. Elements are compared using ( = ).
remove_if cmp l
is similar to remove
, but with cmp
used instead of ( = ).
remove_at i l
returns the list l
without the element at index i
.
remove_all l x
is similar to remove
but removes all elements that are equal to x
and not only the first one.
take n l
returns up to the n
first elements from list l
, if available.
ntake n l
cuts l
into lists of size at most n
. n
must be > 0.
drop n l
returns l
without the first n
elements, or the empty list if l
have less than n
elements.
takedrop n l
is equivalent to (take n l, drop n l)
but is done in one pass.
take_while p xs
returns the (possibly empty) longest prefix of elements of xs
that satisfy the predicate p
.
drop_while p xs
returns the suffix remaining after take_while p xs
.
span
, applied to a predicate p
and a list xs
, returns a tuple where first element is longest prefix (possibly empty) of xs of elements that satisfy p and second element is the remainder of the list. This is equivalent to (take_while p xs, drop_while p xs)
, but is done in one pass.
fold_while p f init l
, accumulates elements x
of list l
using function f
, as long as predicate p acc x
holds. At the end, the accumulated value along with the remaining part of the list are returned.
nsplit
, applied to a predicate p
and a list xs
, returns a list of lists. xs
is split when p x
is true and x
is excluded from the result.
If elements that satisfy p
are consecutive, or at the beginning or end of the input list, the output list will contain empty lists marking their position. For example, split (fun n -> n<0) [-1;2;-2;-3;4;-5]
is [[];[2];[];[4];[]]
. This is consistent with the behavior of String.nsplit
, where String.nsplit ";" "1;2;;3;" = ["1";"2";"";"3";""]
.
Note that for any xss : 'a list list
and sep : 'a
, we always have that flatten (interleave [sep] (nsplit ((=) sep) xss))
is xss
.
The group_consecutive
function takes a list and returns a list of lists such that the concatenation of the result is equal to the argument. Moreover, each sublist in the result contains only equal elements. For example, group_consecutive (=) [3;3;4;3;3] = [[3;3];[4];[3;3]]
.
Note: In the next major version, this function is intended to replace the current group
, which also sorts its input before grouping, and which will therefore be renamed into something more pertinent, such as classify
, regroup
, or group_sort
.
interleave ~first ~last sep [a0;a1;a2;...;an]
returns first; a0; sep; a1; sep; a2; sep; ...; sep; an; last
.
Abstraction layer.
val enum : 'a list -> 'a BatEnum.t
Returns an enumeration of the elements of a list. This enumeration may be used to visit elements of the list in forward order (i.e. from the first element to the last one).
val of_enum : 'a BatEnum.t -> 'a list
Build a list from an enumeration. In the result, elements appear in the same order as they did in the source enumeration.
val backwards : 'a list -> 'a BatEnum.t
Returns an enumeration of the elements of a list. This enumeration may be used to visit elements of the list in backwards order (i.e. from the last element to the first one).
val of_backwards : 'a BatEnum.t -> 'a list
Build a list from an enumeration. The first element of the enumeration becomes the last element of the list, the second element of the enumeration becomes the second-to-last element of the list...
Transform a list of pairs into a pair of lists: split [(a0,b0); (a1,b1); ...; (an,bn)]
is ([a0; a1; ...; an], [b0;
b1; ...; bn])
. Tail-recursive.
Transform a pair of lists into a list of pairs: combine [a0; a1; ...; an] [b0; b1; ...; bn]
is [(a0,b0); (a1,b1); ...; (an,bn)]
.
Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, Pervasives
.compare is a suitable comparison function. The resulting list is sorted in increasing order. List.sort
is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space.
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as List
.sort, but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order) .
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as List
.sort or List
.stable_sort, whichever is faster on typical input.
Merge two lists: Assuming that l1
and l2
are sorted according to the comparison function cmp
, merge cmp l1 l2
will return a sorted list containing all the elements of l1
and l2
. If several elements compare equal, the elements of l1
will be before the elements of l2
. Not tail-recursive (sum of the lengths of the arguments).
sort_uniq cmp l
returns the list l
sorted and without any duplicate element. cmp
is a usual comparison function providing total order.
This function takes O(n log n) time.
group cmp l
returns list of groups and each group consists of elements judged equal by comparison function cmp
. Groups in the resulting list appear in order given by cmp
. All groups are always nonempty. group
returns []
only if l
is empty.
For example group cmp [f;c;b;e;d;a]
can give [[a;b];[c];[d;e;f]]
if following conditions are met: cmp a b = 0
, cmp b c = -1
, cmp c d = -1
, cmp d e = 0
, ...
See the note on group_consecutive
.
Different from List.combine
, this returns every pair of elements formed out of the two lists. cartesian_product [a0; a1; ...; an] [b0; b1; ...; bn] =
[(a0,b0);(a0,b1); ...; (a0,bn); (a1,b0); ..; (a1, bn);
...; (an,bn)]
. The lists can be of unequal size.
Given n lists, return the n-way cartesian product of these lists. Given [a;b];[c];[d;e;f]
, returns [a;c;d];[a;c;e];[a;c;f];[b;c;d];[b;c;e];[b;c;f]
, all ways of choosing one element from each input list.
Transposes a list of lists, turning rows of the input into columns of the output and vice versa.
val print : ?first:string -> ?last:string -> ?sep:string ->
('a BatInnerIO.output -> 'b -> unit) -> 'a BatInnerIO.output -> 'b list -> unit
Print the contents of a list
val ord : 'a BatOrd.ord -> 'a list BatOrd.ord
val compare : 'a BatOrd.comp -> 'a list BatOrd.comp
Comparison and equality for lists based on element comparison and equality
module Ord (T : BatOrd.Ord) : BatOrd.Ord with type t = T.t list
module Comp (T : BatOrd.Comp) : BatOrd.Comp with type t = T.t list
Return the n
-th element of the given list. The first element (head of the list) is at position 0. Return None
if the list is too short. Raise Invalid_argument "List.nth"
if n
is negative.
obsolete, as take_while
obsolete, as drop_while
The following modules replace functions defined in List
with functions behaving slightly differently but having the same name. This is by design: the functions are meant to override the corresponding functions of List
.
module Exceptionless : sig ... end
Exceptionless counterparts for error-raising operations
module Infix : sig ... end
module Labels : sig ... end
Operations on List
with labels.