Module Base.Sequence
A sequence of elements that can be produced one at a time, on demand, normally with no sharing.
The elements are computed on demand, possibly repeating work if they are demanded multiple times. A sequence can be built by unfolding from some initial state, which will in practice often be other containers.
Most functions constructing a sequence will not immediately compute any elements of the sequence. These functions will always return in O(1), but traversing the resulting sequence may be more expensive. The most they will do immediately is generate a new internal state and a new step function.
Functions that transform existing sequences sometimes have to reconstruct some suffix of the input sequence, even if it is unmodified. For example, calling drop 1 will return a sequence with a slightly larger state and whose elements all cost slightly more to traverse. Because this is sometimes undesirable (for example, applying drop
1 n times will cost O(n) per element traversed in the result), there are also more eager versions of many functions (whose names are suffixed with _eagerly) that do more work up front. A function has the _eagerly suffix iff it matches both of these conditions:
- It might consume an element from an input
tbefore returning.
- It only returns a
t(not paired with something else, not wrapped in anoption, etc.). If it returns anything other than atand it has at least onetinput, it's probably demanding elements from the inputtanyway.
Only *_exn functions can raise exceptions, except if the function underlying the sequence (the f passed to unfold) raises, in which case the exception will cascade.
val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> intval equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> boolval sexp_of_t : ('a -> Sexp.t) -> 'a t -> Sexp.t
type 'a sequence= 'a t
include Indexed_container.S1 with type 'a t := 'a t
include Container.S1
val mem : 'a t -> 'a -> equal:('a -> 'a -> bool) -> boolChecks whether the provided element is there, using
equal.
val length : 'a t -> intval is_empty : 'a t -> boolval iter : 'a t -> f:('a -> unit) -> unitval fold : 'a t -> init:'accum -> f:('accum -> 'a -> 'accum) -> 'accumfold t ~init ~freturnsf (... f (f (f init e1) e2) e3 ...) en, wheree1..enare the elements oft
val fold_result : 'a t -> init:'accum -> f:('accum -> 'a -> ('accum, 'e) Result.t) -> ('accum, 'e) Result.tfold_result t ~init ~fis a short-circuiting version offoldthat runs in theResultmonad. Iffreturns anError _, that value is returned without any additional invocations off.
val fold_until : 'a t -> init:'accum -> f:('accum -> 'a -> ('accum, 'final) Base__.Container_intf.Continue_or_stop.t) -> finish:('accum -> 'final) -> 'finalfold_until t ~init ~f ~finishis a short-circuiting version offold. IffreturnsStop _the computation ceases and results in that value. IffreturnsContinue _, the fold will proceed. Iffnever returnsStop _, the final result is computed byfinish.Example:
type maybe_negative = | Found_negative of int | All_nonnegative of { sum : int } (** [first_neg_or_sum list] returns the first negative number in [list], if any, otherwise returns the sum of the list. *) let first_neg_or_sum = List.fold_until ~init:0 ~f:(fun sum x -> if x < 0 then Stop (Found_negative x) else Continue (sum + x)) ~finish:(fun sum -> All_nonnegative { sum }) ;; let x = first_neg_or_sum [1; 2; 3; 4; 5] val x : maybe_negative = All_nonnegative {sum = 15} let y = first_neg_or_sum [1; 2; -3; 4; 5] val y : maybe_negative = Found_negative -3
val exists : 'a t -> f:('a -> bool) -> boolReturns
trueif and only if there exists an element for which the provided function evaluates totrue. This is a short-circuiting operation.
val for_all : 'a t -> f:('a -> bool) -> boolReturns
trueif and only if the provided function evaluates totruefor all elements. This is a short-circuiting operation.
val count : 'a t -> f:('a -> bool) -> intReturns the number of elements for which the provided function evaluates to true.
val sum : (module Base__.Container_intf.Summable with type t = 'sum) -> 'a t -> f:('a -> 'sum) -> 'sumReturns the sum of
f ifor alliin the container.
val find : 'a t -> f:('a -> bool) -> 'a optionReturns as an
optionthe first element for whichfevaluates to true.
val find_map : 'a t -> f:('a -> 'b option) -> 'b optionReturns the first evaluation of
fthat returnsSome, and returnsNoneif there is no such element.
val to_list : 'a t -> 'a listval to_array : 'a t -> 'a arrayval min_elt : 'a t -> compare:('a -> 'a -> int) -> 'a optionReturns a minimum (resp maximum) element from the collection using the provided
comparefunction, orNoneif the collection is empty. In case of a tie, the first element encountered while traversing the collection is returned. The implementation usesfoldso it has the same complexity asfold.
val max_elt : 'a t -> compare:('a -> 'a -> int) -> 'a option
val foldi : ('a t, 'a, _) Base__.Indexed_container_intf.foldival iteri : ('a t, 'a) Base__.Indexed_container_intf.iterival existsi : 'a t -> f:(int -> 'a -> bool) -> boolval for_alli : 'a t -> f:(int -> 'a -> bool) -> boolval counti : 'a t -> f:(int -> 'a -> bool) -> intval findi : 'a t -> f:(int -> 'a -> bool) -> (int * 'a) optionval find_mapi : 'a t -> f:(int -> 'a -> 'b option) -> 'b option
include Monad.S with type 'a t := 'a t
include Base__.Monad_intf.S_without_syntax with type 'a t := 'a t
module Monad_infix : Base__.Monad_intf.Infix with type 'a t := 'a tval return : 'a -> 'a treturn vreturns the (trivial) computation that returns v.
val empty : _ temptyis a sequence with no elements.
val next : 'a t -> ('a * 'a t) optionnextreturns the next element of a sequence and the next tail if the sequence is not finished.
module Step : sig ... endA
Stepdescribes the next step of the sequence construction.Doneindicates the sequence is finished.Skipindicates the sequence continues with another state without producing the next element yet.Yieldoutputs an element and introduces a new state.
val unfold_step : init:'s -> f:('s -> ('a, 's) Step.t) -> 'a tunfold_step ~init ~fconstructs a sequence by giving an initial stateinitand a functionfexplaining how to continue the next step from a given state.
val unfold : init:'s -> f:('s -> ('a * 's) option) -> 'a tunfold ~init fis a simplified version ofunfold_stepthat does not allowSkip.
val unfold_with : 'a t -> init:'s -> f:('s -> 'a -> ('b, 's) Step.t) -> 'b tunfold_with t ~init ~ffolds a state through the sequencetto create a new sequence
val unfold_with_and_finish : 'a t -> init:'s_a -> running_step:('s_a -> 'a -> ('b, 's_a) Step.t) -> inner_finished:('s_a -> 's_b) -> finishing_step:('s_b -> ('b, 's_b) Step.t) -> 'b tunfold_with_and_finish t ~init ~running_step ~inner_finished ~finishing_stepfolds a state throughtto create a new sequence (likeunfold_with t ~init ~f:running_step), and then continues the new sequence by unfolding the final state (likeunfold_step ~init:(inner_finished final_state) ~f:finishing_step).
val nth : 'a t -> int -> 'a optionReturns the nth element.
val nth_exn : 'a t -> int -> 'aval folding_map : 'a t -> init:'b -> f:('b -> 'a -> 'b * 'c) -> 'c tfolding_mapis a version ofmapthat threads an accumulator through calls tof.
val folding_mapi : 'a t -> init:'b -> f:(int -> 'b -> 'a -> 'b * 'c) -> 'c tval mapi : 'a t -> f:(int -> 'a -> 'b) -> 'b tval filteri : 'a t -> f:(int -> 'a -> bool) -> 'a tval filter : 'a t -> f:('a -> bool) -> 'a tval merge : 'a t -> 'a t -> compare:('a -> 'a -> int) -> 'a tmerge t1 t2 ~comparemerges two sorted sequencest1andt2, returning a sorted sequence, all according tocompare. If two elements are equal, the one fromt1is preferred. The behavior is undefined if the inputs aren't sorted.
module Merge_with_duplicates_element : sig ... endval merge_with_duplicates : 'a t -> 'b t -> compare:('a -> 'b -> int) -> ('a, 'b) Merge_with_duplicates_element.t tmerge_with_duplicates_element t1 t2 ~compareis likemerge, except that for each element it indicates which input(s) the element comes from, usingMerge_with_duplicates_element.
val hd : 'a t -> 'a optionval hd_exn : 'a t -> 'aval tl : 'a t -> 'a t optiontl tandtl_eagerly_exn timmediately evaluates the first element oftand returns the unevaluated tail.
val tl_eagerly_exn : 'a t -> 'a tval find_exn : 'a t -> f:('a -> bool) -> 'afind_exn t ~freturns the first element oftthat satisfiesf. It raises if there is no such element.
val for_alli : 'a t -> f:(int -> 'a -> bool) -> boolLike
for_all, but passes the index as an argument.
val append : 'a t -> 'a t -> 'a tappend t1 t2first produces the elements oft1, then produces the elements oft2.
val concat : 'a t t -> 'a tconcat ttproduces the elements of each inner sequence sequentially. If any inner sequences are infinite, elements of subsequent inner sequences will not be reached.
val concat_mapi : 'a t -> f:(int -> 'a -> 'b t) -> 'b tconcat_mapi t ~fis like concat_map, but passes the index as an argument.
val interleave : 'a t t -> 'a tinterleave ttproduces each element of the inner sequences oftteventually, even if any or all of the inner sequences are infinite. The elements of each inner sequence are produced in order with respect to that inner sequence. The manner of interleaving among the separate inner sequences is deterministic but unspecified.
val round_robin : 'a t list -> 'a tround_robin listis likeinterleave (of_list list), except that the manner of interleaving among the inner sequences is guaranteed to be round-robin. The input sequences may be of different lengths; an empty sequence is dropped from subsequent rounds of interleaving.
val zip : 'a t -> 'b t -> ('a * 'b) tTransforms a pair of sequences into a sequence of pairs. The length of the returned sequence is the length of the shorter input. The remaining elements of the longer input are discarded.
WARNING: Unlike
List.zip, this will not error out if the two input sequences are of different lengths, becausezipmay have already returned some elements by the time this becomes apparent.
val zip_full : 'a t -> 'b t -> [ `Left of 'a | `Both of 'a * 'b | `Right of 'b ] tzip_fullis likezip, but if one sequence ends before the other, then it keeps producing elements from the other sequence until it has ended as well.
val reduce_exn : 'a t -> f:('a -> 'a -> 'a) -> 'areduce_exn f [a1; ...; an]isf (... (f (f a1 a2) a3) ...) an. It fails on the empty sequence.
val reduce : 'a t -> f:('a -> 'a -> 'a) -> 'a optionval group : 'a t -> break:('a -> 'a -> bool) -> 'a list tgroup l ~breakreturns a sequence of lists (i.e., groups) whose concatenation is equal to the original sequence. Each group is broken wherebreakreturns true on a pair of successive elements.Example:
group ~break:(<>) (of_list ['M';'i';'s';'s';'i';'s';'s';'i';'p';'p';'i']) -> of_list [['M'];['i'];['s';'s'];['i'];['s';'s'];['i'];['p';'p'];['i']]
val find_consecutive_duplicate : 'a t -> equal:('a -> 'a -> bool) -> ('a * 'a) optionfind_consecutive_duplicate t ~equalreturns the first pair of consecutive elements(a1, a2)intsuch thatequal a1 a2. They are returned in the same order as they appear int.
val remove_consecutive_duplicates : 'a t -> equal:('a -> 'a -> bool) -> 'a tThe same sequence with consecutive duplicates removed. The relative order of the other elements is unaffected.
val range : ?stride:int -> ?start:[ `inclusive | `exclusive ] -> ?stop:[ `inclusive | `exclusive ] -> int -> int -> int trange ?stride ?start ?stop start_i stop_iis the sequence of integers fromstart_itostop_i, stepping bystride. Ifstride< 0 then we needstart_i>stop_ifor the result to be nonempty (orstart_i>=stop_iin the case where both bounds are inclusive).
val init : int -> f:(int -> 'a) -> 'a tinit n ~fis[(f 0); (f 1); ...; (f (n-1))]. It is an error ifn < 0.
val filter_map : 'a t -> f:('a -> 'b option) -> 'b tfilter_map t ~fproduce mapped elements oftwhich are notNone.
val filter_mapi : 'a t -> f:(int -> 'a -> 'b option) -> 'b tfilter_mapiis just likefilter_map, but it also passes in the index of each element tof.
val filter_opt : 'a option t -> 'a tfilter_opt tproduces the elements oftwhich are notNone.filter_opt t=filter_map t ~f:Fn.id.
val sub : 'a t -> pos:int -> len:int -> 'a tsub t ~pos ~lenis thelen-element subsequence oft, starting atpos. If the sequence is shorter thanpos + len, it returnst[pos] ... t[l-1], wherelis the length of the sequence.
val drop : 'a t -> int -> 'a tdrop t nproduces all elements oftexcept the firstnelements. If there are fewer thannelements int, there is no error; the resulting sequence simply produces no elements. Usually you will probably want to usedrop_eagerlybecause it can be significantly cheaper.
val drop_eagerly : 'a t -> int -> 'a tdrop_eagerly t nimmediately consumes the firstnelements oftand returns the unevaluated tail oft.
val take_while : 'a t -> f:('a -> bool) -> 'a ttake_while t ~fproduces the longest prefix oftfor whichfapplied to each element istrue.
val drop_while : 'a t -> f:('a -> bool) -> 'a tdrop_while t ~fproduces the suffix oftbeginning with the first element oftfor whichfisfalse. Usually you will probably want to usedrop_while_optionbecause it can be significantly cheaper.
val drop_while_option : 'a t -> f:('a -> bool) -> ('a * 'a t) optiondrop_while_option t ~fimmediately consumes the elements fromtuntil the predicateffails and returns the first element that failed along with the unevaluated tail oft. The first element is returned separately because the alternatives would mean forcing the consumer to evaluate the first element again (if the previous state of the sequence is returned) or take on extra cost for each element (if the element is added to the final state of the sequence usingshift_right).
val split_n : 'a t -> int -> 'a list * 'a tsplit_n t nimmediately consumes the firstnelements oftand returns the consumed prefix, as a list, along with the unevaluated tail oft.
val chunks_exn : 'a t -> int -> 'a list tchunks_exn t nproduces lists of elements oft, up tonelements at a time. The last list may contain fewer thannelements. No list contains zero elements. Ifnis not positive, it raises.
val shift_right_with_list : 'a t -> 'a list -> 'a tshift_right_with_list t lproduces the elements ofl, then produces the elements oft. It is better to callshift_right_with_listwith a list of size n thanshift_rightn times; the former will require O(1) work per element produced and the latter O(n) work per element produced.
module Infix : sig ... endval cartesian_product : 'a t -> 'b t -> ('a * 'b) tReturns a sequence with all possible pairs. The stepper function of the second sequence passed as argument may be applied to the same state multiple times, so be careful using
cartesian_productwith expensive or side-effecting functions. If the second sequence is infinite, some values in the first sequence may not be reached.
val interleaved_cartesian_product : 'a t -> 'b t -> ('a * 'b) tReturns a sequence that eventually reaches every possible pair of elements of the inputs, even if either or both are infinite. The step function of both inputs may be applied to the same state repeatedly, so be careful using
interleaved_cartesian_productwith expensive or side-effecting functions.
val intersperse : 'a t -> sep:'a -> 'a tintersperse xs ~sepproducessepbetween adjacent elements ofxs, e.g.,intersperse [1;2;3] ~sep:0 = [1;0;2;0;3].
val cycle_list_exn : 'a list -> 'a tcycle_list_exn xsrepeats the elements ofxsforever. Ifxsis empty, it raises.
val repeat : 'a -> 'a trepeat arepeatsaforever.
val singleton : 'a -> 'a tsingleton aproducesaexactly once.
val delayed_fold : 'a t -> init:'s -> f:('s -> 'a -> k:('s -> 'r) -> 'r) -> finish:('s -> 'r) -> 'rdelayed_foldallows to do an on-demand fold, while maintaining a state.It is possible to exit early by not calling
kinf. It is also possible to callkmultiple times. This results in the rest of the sequence being folded over multiple times, independently.Note that
delayed_fold, when targeting JavaScript, can result in stack overflow as JavaScript doesn't generally have tail call optimization.
val fold_m : bind:('acc_m -> f:('acc -> 'acc_m) -> 'acc_m) -> return:('acc -> 'acc_m) -> 'elt t -> init:'acc -> f:('acc -> 'elt -> 'acc_m) -> 'acc_mfold_mis a monad-friendly version offold. Supply it with the monad'sreturnandbind, and it will chain them through the computation.
val iter_m : bind:('unit_m -> f:(unit -> 'unit_m) -> 'unit_m) -> return:(unit -> 'unit_m) -> 'elt t -> f:('elt -> 'unit_m) -> 'unit_miter_mis a monad-friendly version ofiter. Supply it with the monad'sreturnandbind, and it will chain them through the computation.
val to_list_rev : 'a t -> 'a listto_list_rev treturns a list of the elements oft, in reverse order. It is faster thanto_list.
val of_list : 'a list -> 'a tval of_lazy : 'a t Lazy.t -> 'a tof_lazy t_lazyproduces a sequence that forcest_lazythe first time it needs to compute an element.
val memoize : 'a t -> 'a tmemoize tproduces each element oft, but also memoizes them so that if you consume the same element multiple times it is only computed once. It's a non-eager version offorce_eagerly.
val force_eagerly : 'a t -> 'a tforce_eagerly tprecomputes the sequence. It is behaviorally equivalent toof_list (to_list t), but may at some point have a more efficient implementation. It's an eager version ofmemoize.
val bounded_length : _ t -> at_most:int -> [ `Is of int | `Greater ]bounded_length ~at_most treturns`Is leniflen = length t <= at_most, and otherwise returns`Greater. Walks through only as much of the sequence as necessary. Always returns`Greaterifat_most < 0.
val length_is_bounded_by : ?min:int -> ?max:int -> _ t -> boollength_is_bounded_by ~min ~max treturns true ifmin <= length tandlength t <= maxWhenminormaxare not provided, the check for that bound is omitted. Walks through only as much of the sequence as necessary.
val of_seq : 'a Base__.Import.Caml.Seq.t -> 'a tval to_seq : 'a t -> 'a Base__.Import.Caml.Seq.t
module Generator : sig ... endmodule Expert : sig ... endThe functions in
Expertexpose internal structure which is normally meant to be hidden. For example, at least whenfis purely functional, it is not intended for client code to distinguish between