Module Sequence
Simple and Efficient Iterators
type +'a t= ('a -> unit) -> unitA sequence of values of type
'a. If you give it a function'a -> unitit will be applied to every element of the sequence successively.
type +'a sequence= 'a t
Build a sequence
val from_iter : (('a -> unit) -> unit) -> 'a tBuild a sequence from a iter function
val from_fun : (unit -> 'a option) -> 'a tCall the function repeatedly until it returns None. This sequence is transient, use
persistentif needed!
val empty : 'a tEmpty sequence. It contains no element.
val singleton : 'a -> 'a tSingleton sequence, with exactly one element.
val doubleton : 'a -> 'a -> 'a tSequence with exactly two elements
val init : (int -> 'a) -> 'a tinit fis the infinite sequencef 0; f 1; f 2; ….- since
- 0.9
val repeat : 'a -> 'a tInfinite sequence of the same element. You may want to look at
takeand the likes if you iterate on it.
val iterate : ('a -> 'a) -> 'a -> 'a titerate f xis the infinite sequencex, f(x), f(f(x)), ...
val forever : (unit -> 'b) -> 'b tSequence that calls the given function to produce elements. The sequence may be transient (depending on the function), and definitely is infinite. You may want to use
takeandpersistent.
Consume a sequence
val iter : ('a -> unit) -> 'a t -> unitConsume the sequence, passing all its arguments to the function. Basically
iter f seqis justseq f.
val iteri : (int -> 'a -> unit) -> 'a t -> unitIterate on elements and their index in the sequence
val fold : ('a -> 'b -> 'a) -> 'a -> 'b t -> 'aFold over elements of the sequence, consuming it
val foldi : ('a -> int -> 'b -> 'a) -> 'a -> 'b t -> 'aFold over elements of the sequence and their index, consuming it
val fold_map : ('acc -> 'a -> 'acc * 'b) -> 'acc -> 'a t -> 'b tfold_map f acc lis likemap, but it carries some state as infold. The state is not returned, it is just used to thread some information to the map function.- since
- 0.9
val fold_filter_map : ('acc -> 'a -> 'acc * 'b option) -> 'acc -> 'a t -> 'b tfold_filter_map f acc lis afold_map-like function, but the function can choose to skip an element by retuningNone.- since
- 0.9
val map_by_2 : ('a -> 'a -> 'a) -> 'a t -> 'a tMap objects two by two. lazily. The last element is kept in the sequence if the count is odd.
- since
- 0.7
val for_all : ('a -> bool) -> 'a t -> boolDo all elements satisfy the predicate?
val exists : ('a -> bool) -> 'a t -> boolExists there some element satisfying the predicate?
val mem : ?eq:('a -> 'a -> bool) -> 'a -> 'a t -> boolIs the value a member of the sequence?
- parameter eq
the equality predicate to use (default
(=))
- since
- 0.5
val find : ('a -> 'b option) -> 'a t -> 'b optionFind the first element on which the function doesn't return
None- since
- 0.5
val find_pred : ('a -> bool) -> 'a t -> 'a optionfind_pred p lfinds the first element oflthat satisfiesp, or returnsNoneif no element satisfiesp- since
- 0.9
val find_pred_exn : ('a -> bool) -> 'a t -> 'aUnsafe version of
find_pred- raises Not_found
if no such element is found
- since
- 0.9
val length : 'a t -> intHow long is the sequence? Forces the sequence.
val is_empty : 'a t -> boolIs the sequence empty? Forces the sequence.
Transform a sequence
val append : 'a t -> 'a t -> 'a tAppend two sequences. Iterating on the result is like iterating on the first, then on the second.
val append_l : 'a t list -> 'a tAppend sequences. Iterating on the result is like iterating on the each sequence of the list in order.
- since
- 0.11
val flat_map : ('a -> 'b t) -> 'a t -> 'b tMonadic bind. Intuitively, it applies the function to every element of the initial sequence, and calls
concat. FormerlyflatMap- since
- 0.5
val flat_map_l : ('a -> 'b list) -> 'a t -> 'b tConvenience function combining
flat_mapandof_list- since
- 0.9
val seq_list : 'a t list -> 'a list tseq_list lreturns all the ways to pick one element in each sub-sequence inl. Assumes the sub-sequences can be iterated on several times.- since
- 0.11
val seq_list_map : ('a -> 'b t) -> 'a list -> 'b list tseq_list_map f lmapsfover every element ofl, then callsseq_list- since
- 0.11
val filter_map : ('a -> 'b option) -> 'a t -> 'b tMap and only keep non-
Noneelements Formerlyfmap- since
- 0.5
val filter_mapi : (int -> 'a -> 'b option) -> 'a t -> 'b tMap with indices, and only keep non-
Noneelements- since
- 0.11
val filter_count : ('a -> bool) -> 'a t -> intCount how many elements satisfy the given predicate
- since
- 1.0
val keep_some : 'a option t -> 'a tfilter_some lretains only elements of the formSome x. Same asfilter_map (fun x->x)- since
- 1.0
Caching
val persistent : 'a t -> 'a tIterate on the sequence, storing elements in an efficient internal structure.. The resulting sequence can be iterated on as many times as needed. Note: calling persistent on an already persistent sequence will still make a new copy of the sequence!
val persistent_lazy : 'a t -> 'a tLazy version of
persistent. When callingpersistent_lazy s, a new sequences'is immediately returned (without actually consumings) in constant time; the first times'is iterated on, it also consumessand caches its content into a inner data structure that will backs'for future iterations.warning: on the first traversal of
s', if the traversal is interrupted prematurely (take, etc.) thens'will not be memorized, and the next call tos'will traversesagain.
Misc
val sort : ?cmp:('a -> 'a -> int) -> 'a t -> 'a tSort the sequence. Eager, O(n) ram and O(n ln(n)) time. It iterates on elements of the argument sequence immediately, before it sorts them.
val sort_uniq : ?cmp:('a -> 'a -> int) -> 'a t -> 'a tSort the sequence and remove duplicates. Eager, same as
sort
val sorted : ?cmp:('a -> 'a -> int) -> 'a t -> boolChecks whether the sequence is sorted. Eager, same as
sort.- since
- 0.9
val group_succ_by : ?eq:('a -> 'a -> bool) -> 'a t -> 'a list tGroup equal consecutive elements. Linear time. Formerly synonym to
group.- since
- 0.6
val group_by : ?hash:('a -> int) -> ?eq:('a -> 'a -> bool) -> 'a t -> 'a list tGroup equal elements, disregarding their order of appearance. The result sequence is traversable as many times as required. precondition: for any
xandy, ifeq x ythenhash x=hash ymust hold.- since
- 0.6
val count : ?hash:('a -> int) -> ?eq:('a -> 'a -> bool) -> 'a t -> ('a * int) tMap each distinct element to its number of occurrences in the whole seq. Similar to
group_by seq |> map (fun l->List.hd l, List.length l)precondition: for anyxandy, ifeq x ythenhash x=hash ymust hold.- since
- 0.10
val uniq : ?eq:('a -> 'a -> bool) -> 'a t -> 'a tRemove consecutive duplicate elements. Basically this is like
fun seq -> map List.hd (group seq).
val product : 'a t -> 'b t -> ('a * 'b) tCartesian product of the sequences. When calling
product a b, the caller MUST ensure thatbcan be traversed as many times as required (several times), possibly by callingpersistenton it beforehand.
val diagonal_l : 'a list -> ('a * 'a) tAll pairs of distinct positions of the list.
diagonal lwill return the sequence of allList.nth i l, List.nth j lifi < j.- since
- 0.9
val diagonal : 'a t -> ('a * 'a) tAll pairs of distinct positions of the sequence. Iterates only once on the sequence, which must be finite.
- since
- 0.9
val join : join_row:('a -> 'b -> 'c option) -> 'a t -> 'b t -> 'c tjoin ~join_row a bcombines every element ofawith every element ofbusingjoin_row. Ifjoin_rowreturns None, then the two elements do not combine. Assume thatballows for multiple iterations.
val join_by : ?eq:'key equal -> ?hash:'key hash -> ('a -> 'key) -> ('b -> 'key) -> merge:('key -> 'a -> 'b -> 'c option) -> 'a t -> 'b t -> 'c tjoin key1 key2 ~mergeis a binary operation that takes two sequencesaandb, projects their elements resp. withkey1andkey2, and combine values(x,y)from(a,b)with the samekeyusingmerge. IfmergereturnsNone, the combination of values is discarded. precondition: for anyxandy, ifeq x ythenhash x=hash ymust hold.- since
- 0.10
val join_all_by : ?eq:'key equal -> ?hash:'key hash -> ('a -> 'key) -> ('b -> 'key) -> merge:('key -> 'a list -> 'b list -> 'c option) -> 'a t -> 'b t -> 'c tjoin_all_by key1 key2 ~mergeis a binary operation that takes two sequencesaandb, projects their elements resp. withkey1andkey2, and, for each keykoccurring in at least one of them:- compute the list
l1of elements ofathat map tok - compute the list
l2of elements ofbthat map tok - call
merge k l1 l2. IfmergereturnsNone, the combination of values is discarded, otherwise it returnsSome candcis inserted in the result.
- since
- 0.10
- compute the list
val group_join_by : ?eq:'a equal -> ?hash:'a hash -> ('b -> 'a) -> 'a t -> 'b t -> ('a * 'b list) tgroup_join_by key2associates to every elementxof the first sequence, all the elementsyof the second sequence such thateq x (key y). Elements of the first sequences without corresponding values in the second one are mapped to[]precondition: for anyxandy, ifeq x ythenhash x=hash ymust hold.- since
- 0.10
val inter : ?eq:'a equal -> ?hash:'a hash -> 'a t -> 'a t -> 'a tIntersection of two collections. Each element will occur at most once in the result. Eager. precondition: for any
xandy, ifeq x ythenhash x=hash ymust hold.- since
- 0.10
val union : ?eq:'a equal -> ?hash:'a hash -> 'a t -> 'a t -> 'a tUnion of two collections. Each element will occur at most once in the result. Eager. precondition: for any
xandy, ifeq x ythenhash x=hash ymust hold.- since
- 0.10
val subset : ?eq:'a equal -> ?hash:'a hash -> 'a t -> 'a t -> boolsubset a breturnstrueif all elements ofabelong tob. Eager. precondition: for anyxandy, ifeq x ythenhash x=hash ymust hold.- since
- 0.10
val unfoldr : ('b -> ('a * 'b) option) -> 'b -> 'a tunfoldr f bwill applyftob. If it yieldsSome (x,b')thenxis returned and unfoldr recurses withb'.
val max : ?lt:('a -> 'a -> bool) -> 'a t -> 'a optionMax element of the sequence, using the given comparison function.
- returns
None if the sequence is empty, Some
mwheremis the maximal element otherwise
val max_exn : ?lt:('a -> 'a -> bool) -> 'a t -> 'aUnsafe version of
max- raises Not_found
if the sequence is empty
- since
- 0.10
val min : ?lt:('a -> 'a -> bool) -> 'a t -> 'a optionMin element of the sequence, using the given comparison function. see
maxfor more details.
val min_exn : ?lt:('a -> 'a -> bool) -> 'a t -> 'aUnsafe version of
min- raises Not_found
if the sequence is empty
- since
- 0.10
val sum : int t -> intSum of elements
- since
- 0.11
val sumf : float t -> floatSum of elements, using Kahan summation
- since
- 0.11
val head : 'a t -> 'a optionFirst element, if any, otherwise
None- since
- 0.5.1
val head_exn : 'a t -> 'aFirst element, if any, fails
- raises Invalid_argument
if the sequence is empty
- since
- 0.5.1
val take : int -> 'a t -> 'a tTake at most
nelements from the sequence. Works on infinite sequences.
val take_while : ('a -> bool) -> 'a t -> 'a tTake elements while they satisfy the predicate, then stops iterating. Will work on an infinite sequence
sif the predicate is false for at least one element ofs.
val fold_while : ('a -> 'b -> 'a * [ `Stop | `Continue ]) -> 'a -> 'b t -> 'aFolds over elements of the sequence, stopping early if the accumulator returns
('a, `Stop)- since
- 0.5.5
val rev : 'a t -> 'a tReverse the sequence. O(n) memory and time, needs the sequence to be finite. The result is persistent and does not depend on the input being repeatable.
Basic data structures converters
val to_list : 'a t -> 'a listConvert the sequence into a list. Preserves order of elements. This function is tail-recursive, but consumes 2*n memory. If order doesn't matter to you, consider
to_rev_list.
val to_rev_list : 'a t -> 'a listGet the list of the reversed sequence (more efficient than
to_list)
val of_list : 'a list -> 'a tval on_list : ('a t -> 'b t) -> 'a list -> 'b liston_list f lis equivalent toto_list @@ f @@ of_list l.- since
- 0.5.2
val pair_with_idx : 'a t -> (int * 'a) tSimilar to
zip_ibut returns a normal sequence of tuples- since
- 0.11
val to_array : 'a t -> 'a arrayConvert to an array. Currently not very efficient because an intermediate list is used.
val of_array : 'a array -> 'a tval of_array_i : 'a array -> (int * 'a) tElements of the array, with their index
val array_slice : 'a array -> int -> int -> 'a tarray_slice a i jSequence of elements whose indexes range fromitoj
val of_opt : 'a option -> 'a tIterate on 0 or 1 values.
- since
- 0.5.1
val of_stream : 'a Stream.t -> 'a tSequence of elements of a stream (usable only once)
val to_stream : 'a t -> 'a Stream.tConvert to a stream. linear in memory and time (a copy is made in memory)
val to_stack : 'a Stack.t -> 'a t -> unitPush elements of the sequence on the stack
val of_stack : 'a Stack.t -> 'a tSequence of elements of the stack (same order as
Stack.iter)
val to_queue : 'a Queue.t -> 'a t -> unitPush elements of the sequence into the queue
val of_queue : 'a Queue.t -> 'a tSequence of elements contained in the queue, FIFO order
val hashtbl_add : ('a, 'b) Hashtbl.t -> ('a * 'b) t -> unitAdd elements of the sequence to the hashtable, with Hashtbl.add
val hashtbl_replace : ('a, 'b) Hashtbl.t -> ('a * 'b) t -> unitAdd elements of the sequence to the hashtable, with Hashtbl.replace (erases conflicting bindings)
val to_hashtbl : ('a * 'b) t -> ('a, 'b) Hashtbl.tBuild a hashtable from a sequence of key/value pairs
val of_hashtbl : ('a, 'b) Hashtbl.t -> ('a * 'b) tSequence of key/value pairs from the hashtable
val hashtbl_keys : ('a, 'b) Hashtbl.t -> 'a tval hashtbl_values : ('a, 'b) Hashtbl.t -> 'b tval of_str : string -> char tval to_str : char t -> stringval concat_str : string t -> stringConcatenate strings together, eagerly. Also see
intersperseto add a separator.- since
- 0.5
exceptionOneShotSequenceRaised when the user tries to iterate several times on a transient iterator
val of_in_channel : Pervasives.in_channel -> char tIterates on characters of the input (can block when one iterates over the sequence). If you need to iterate several times on this sequence, use
persistent.- raises OneShotSequence
when used more than once.
val to_buffer : char t -> Buffer.t -> unitCopy content of the sequence into the buffer
val int_range : start:int -> stop:int -> int tIterator on integers in
start...stopby steps 1. Also see(--)for an infix version.
val int_range_dec : start:int -> stop:int -> int tIterator on decreasing integers in
stop...startby steps -1. See(--^)for an infix version
val int_range_by : step:int -> int -> int -> int tint_range_by ~step i jis the range starting ati, includingj, where the difference between successive elements isstep. use a negativestepfor a decreasing sequence.- raises Invalid_argument
if
step=0
val bools : bool tIterates on
trueandfalse- since
- 0.7
val of_set : (module Set.S with type elt = 'a and type t = 'b) -> 'b -> 'a tConvert the given set to a sequence. The set module must be provided.
val to_set : (module Set.S with type elt = 'a and type t = 'b) -> 'a t -> 'bConvert the sequence to a set, given the proper set module
type 'a gen= unit -> 'a optiontype 'a klist= unit -> [ `Nil | `Cons of 'a * 'a klist ]
Functorial conversions between sets and sequences
module Set : sig ... endConversion between maps and sequences.
module Map : sig ... endInfinite sequences of random values
val random_int : int -> int tInfinite sequence of random integers between 0 and the given higher bound (see Random.int)
val random_bool : bool tInfinite sequence of random bool values
val random_float : float -> float tval random_array : 'a array -> 'a tSequence of choices of an element in the array
val random_list : 'a list -> 'a tInfinite sequence of random elements of the list. Basically the same as
random_array.
Sampling
val sample : int -> 'a t -> 'a arraysample n seqreturns k samples ofseq, with uniform probability. It will consume the sequence and use O(n) memory.It returns an array of size
min (length seq) n.- since
- 0.7
Infix functions
module Infix : sig ... endinclude module type of Infix
val (--) : int -> int -> int ta -- bis the range of integers fromatob, both included, in increasing order. It will therefore be empty ifa > b.
val (--^) : int -> int -> int ta --^ bis the range of integers frombtoa, both included, in decreasing order (starts froma). It will therefore be empty ifa < b.
Pretty printing of sequences
val pp_seq : ?sep:string -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unitPretty print a sequence of
'a, using the given pretty printer to print each elements. An optional separator string can be provided.
val pp_buf : ?sep:string -> (Buffer.t -> 'a -> unit) -> Buffer.t -> 'a t -> unitPrint into a buffer
val to_string : ?sep:string -> ('a -> string) -> 'a t -> stringPrint into a string
Basic IO
Very basic interface to manipulate files as sequence of chunks/lines. The sequences take care of opening and closing files properly; every time one iterates over a sequence, the file is opened/closed again.
Example: copy a file "a" into file "b", removing blank lines:
Sequence.(IO.lines_of "a" |> filter (fun l-> l<> "") |> IO.write_lines "b");;By chunks of 4096 bytes:
Sequence.IO.(chunks_of ~size:4096 "a" |> write_to "b");;Read the lines of a file into a list:
Sequence.IO.lines "a" |> Sequence.to_list- since
- 0.5.1
module IO : sig ... end