OCaml package documentation
+-
+
- containers 3.9 +
- containers-data 3.9 +
- containers-thread 3.9 +
diff --git a/3.10/containers-data/CCBV/.dummy b/3.10/containers-data/CCBV/.dummy new file mode 100644 index 00000000..e69de29b diff --git a/3.10/containers-data/CCBV/index.html b/3.10/containers-data/CCBV/index.html new file mode 100644 index 00000000..e2edb5f6 --- /dev/null +++ b/3.10/containers-data/CCBV/index.html @@ -0,0 +1,3 @@ + +
CCBVImperative Bitvectors.
A bitvector is stored in some form of internal array (on the heap). Is it a bit similar to a more storage-efficient version of bool
+ CCVector.vector, with additional operations.
BREAKING CHANGES since 1.2: size is now stored along with the bitvector. Some functions have a new signature.
The size of the bitvector used to be rounded up to the multiple of 30 or 62. In other words some functions such as iter would iterate on more bits than what was originally asked for. This is not the case anymore.
val empty : unit -> tEmpty bitvector. Length is 0.
val create : size:int -> bool -> tCreate a bitvector of given size, with given default value. Length of result is size.
val init : int -> ( int -> bool ) -> tinit len f initializes a bitvector of length len, where bit i is true iff f i is.
val cardinal : t -> intNumber of bits set to one, seen as a set of bits.
val length : t -> intSize of underlying bitvector. This is not related to the underlying implementation. Changed at 1.2
val capacity : t -> intThe number of bits this bitvector can store without resizing.
val resize : t -> int -> unitResize the BV so that it has the specified length. This can grow the underlying array, but it will not shrink it, to minimize memory traffic.
val resize_minimize_memory : t -> int -> unitSame as resize, but this can also shrink the underlying array if this reduces the size.
val is_empty : t -> boolAre there any true bits?
val set : t -> int -> unitSet i-th bit, extending the bitvector if needed.
val get : t -> int -> boolIs the i-th bit true? Return false if the index is too high.
val reset : t -> int -> unitSet i-th bit to 0, extending the bitvector if needed.
val set_bool : t -> int -> bool -> unitSet or reset i-th bit.
val flip : t -> int -> unitFlip i-th bit, extending the bitvector if needed.
val clear : t -> unitSet every bit to 0. Does not change the length.
val clear_and_shrink : t -> unitSet every bit to 0, and set length to 0.
val iter : t -> ( int -> bool -> unit ) -> unitIterate on all bits.
val iter_true : t -> ( int -> unit ) -> unitIterate on bits set to 1.
val to_list : t -> int listList of indexes that are true.
val to_sorted_list : t -> int listSame as to_list, but also guarantees the list is sorted in increasing order.
val of_list : int list -> tFrom a list of true bits.
The bits are interpreted as indices into the returned bitvector, so the final bitvector bv will have length bv equal to 1 more than max of list indices.
val first : t -> int optionFirst set bit, or return None. Changed type at 1.2
val first_exn : t -> intFirst set bit, or
val filter : t -> ( int -> bool ) -> unitfilter bv p only keeps the true bits of bv whose index satisfies p index. Length is unchanged.
val negate_self : t -> unitnegate_self t flips all of the bits in t. Length is unchanged.
union_into ~into bv sets into to the union of itself and bv. Also updates the length of into to be at least length bv.
inter_into ~into bv sets into to the intersection of itself and bv. Also updates the length of into to be at most length bv.
After executing:
length ~into' = min (length into) (length bv).for all i: get into' ==> get into i /\ get bv iunion bv1 bv2 returns the union of the two sets. The length of the result is the max of the inputs' lengths.
inter bv1 bv2 returns the intersection of the two sets. The length of the result is the min of the inputs' lengths.
diff_into ~into t modifies into with only the bits set but not in t.
val select : t -> 'a array -> 'a listselect arr bv selects the elements of arr whose index corresponds to a true bit in bv. If bv is too short, elements of arr with too high an index cannot be selected and are therefore not selected.
val selecti : t -> 'a array -> ('a * int) listSame as select, but selected elements are paired with their indexes.
Bitwise comparison, including the size (equal a b implies length a=length b).
val pp : Stdlib.Format.formatter -> t -> unitPrint the bitvector as a string of bits.
Make.1-LMake.2-RCCBijection.Makemodule L : OrderedTypemodule R : OrderedTypetype left = L.ttype right = R.tval empty : tval is_empty : t -> boolAdd left and right correspondence to bijection such that left and right are unique in their respective sets and only correspond to each other.
val cardinal : t -> intNumber of bindings. O(n) time.
Remove the left, right binding if it exists. Return the same bijection otherwise.
Remove the binding with left key if it exists. Return the same bijection otherwise.
Remove the binding with right key if it exists. Return the same bijection otherwise.
CCBijectionFunctor to build a bijection Represents 1-to-1 mappings between two types. Each element from the "left" is mapped to one "right" value, and conversely.
module type OrderedType = sig ... endmodule type S = sig ... endmodule Make
+ (L : OrderedType)
+ (R : OrderedType) :
+ S with type left = L.t and type right = R.tCCBijection.OrderedTypeCCBijection.Sval empty : tval is_empty : t -> boolAdd left and right correspondence to bijection such that left and right are unique in their respective sets and only correspond to each other.
val cardinal : t -> intNumber of bindings. O(n) time.
Remove the left, right binding if it exists. Return the same bijection otherwise.
Remove the binding with left key if it exists. Return the same bijection otherwise.
Remove the binding with right key if it exists. Return the same bijection otherwise.
Make.1-_CCBitField.MakeCreate a new bitfield type
module _ : sig ... endGenerative type of bitfields. Each instantiation of the functor should create a new, incompatible type
val empty : tEmpty bitfields (all bits 0).
val mk_field : unit -> fieldMake a new field.
Prevent new fields from being added. From now on, creating a field will raise Frozen.
CCBitFieldEfficient Bit Field for up to 31 or 61 fiels
This module defines efficient bitfields up to 31 or 61 bits (depending on the architecture) in a relatively type-safe way.
module B = CCBitField.Make(struct end);;
+
+let x = B.mk_field ()
+let y = B.mk_field ()
+let z = B.mk_field ()
+
+let f = B.empty |> B.set x true |> B.set y true;;
+
+assert (not (B.get z f)) ;;
+
+assert (f |> B.set z true |> B.get z);;module type S = sig ... endCCBitField.SGenerative type of bitfields. Each instantiation of the functor should create a new, incompatible type
val empty : tEmpty bitfields (all bits 0).
val mk_field : unit -> fieldMake a new field.
Prevent new fields from being added. From now on, creating a field will raise Frozen.
CCCacheCaches Utils
Particularly useful for memoization. See with_cache and with_cache_rec for more details.
Typical use case: one wants to memoize a function f : 'a -> 'b. Code sample:
let f x =
+ print_endline "call f";
+ x + 1;;
+
+let f' = with_cache (lru 256) f;;
+f' 0;; (* prints *)
+f' 1;; (* prints *)
+f' 0;; (* doesn't print, returns cached value *)val clear : ( _, _ ) t -> unitClear the content of the cache.
Type of the callback that is called once a cached value is found or not. Should never raise.
with_cache c f behaves like f, but caches calls to f in the cache c. It always returns the same value as f x, if f x returns, or raise the same exception. However, f may not be called if x is in the cache.
val with_cache_rec :
+ ?cb:( 'a, 'b ) callback ->
+ ( 'a, 'b ) t ->
+ ( ( 'a -> 'b ) -> 'a -> 'b ) ->
+ 'a ->
+ 'bwith_cache_rec c f is a function that first, applies f to some f' = fix f, such that recursive calls to f' are cached in c. It is similar to with_cache but with a function that takes as first argument its own recursive version. Example (memoized Fibonacci function):
let fib = with_cache_rec (lru 256)
+ (fun fib' n -> match n with
+ | 1 | 2 -> 1
+ | _ -> fib' (n-1) + fib' (n-2)
+ );;
+
+fib 70;;val size : ( _, _ ) t -> intSize of the cache (number of entries). At most linear in the number of entries.
val iter : ( 'a, 'b ) t -> ( 'a -> 'b -> unit ) -> unitIterate on cached values. Should yield size cache pairs.
val add : ( 'a, 'b ) t -> 'a -> 'b -> boolManually add a cached value. Return true if the value has successfully been added, and false if the value was already bound.
val dummy : ( 'a, 'b ) tDummy cache, never stores any value.
Linear cache with the given size. It stores key/value pairs in an array and does linear search at every call, so it should only be used with small size.
Replacing cache of the given size. Equality and hash functions can be parametrized. It's a hash table that handles collisions by replacing the old value with the new (so a cache entry is evicted when another entry with the same hash (modulo size) is added). Never grows wider than the given size.
LRU cache of the given size ("Least Recently Used": keys that have not been used recently are deleted first). Never grows wider than the given size.
CCDequeImperative deque
This structure provides fast access to its front and back elements, with O(1) operations.
val create : unit -> 'a tNew deque.
val clear : _ t -> unitRemove all elements.
val is_empty : 'a t -> boolIs the deque empty?
equal a b checks whether a and b contain the same sequence of elements.
compare a b compares lexicographically a and b.
val length : 'a t -> intNumber of elements. Used to be linear time, now constant time.
val push_front : 'a t -> 'a -> unitPush value at the front.
val push_back : 'a t -> 'a -> unitPush value at the back.
val peek_front : 'a t -> 'aFirst value.
val peek_front_opt : 'a t -> 'a optionFirst value.
val peek_back : 'a t -> 'aLast value.
val peek_back_opt : 'a t -> 'a optionLast value.
val remove_back : 'a t -> unitRemove last value. If the deque is empty do nothing
val remove_front : 'a t -> unitRemove first value. If the deque is empty do nothing
val take_back : 'a t -> 'aTake last value.
val take_back_opt : 'a t -> 'a optionTake last value.
val take_front : 'a t -> 'aTake first value.
val take_front_opt : 'a t -> 'a optionTake first value.
val update_back : 'a t -> ( 'a -> 'a option ) -> unitUpdate last value. If the deque is empty do nothing. If the function returns None, remove last element; if it returns Some x, replace last element with x.
val update_front : 'a t -> ( 'a -> 'a option ) -> unitUpdate first value. If the deque is empty do nothing. Similar to update_back but for the first value.
append_front ~into q adds all elements of q at the front of into. O(length q) in time.
append_back ~into q adds all elements of q at the back of into. O(length q) in time.
val iter : ( 'a -> unit ) -> 'a t -> unitIterate on elements.
val fold : ( 'b -> 'a -> 'b ) -> 'b -> 'a t -> 'bFold on elements.
Create a deque from the sequence. Optional argument deque disappears, use add_iter_back instead.
add_iter_front q seq adds elements of seq into the front of q, in reverse order. O(n) in time, where n is the number of elements to add.
add_iter_back q seq adds elements of seq into the back of q, in order. O(n) in time, where n is the number of elements to add.
val of_list : 'a list -> 'a tConversion from list, in order.
val to_list : 'a t -> 'a listList of elements, in order. Less efficient than to_rev_list.
val to_rev_list : 'a t -> 'a listEfficient conversion to list, in reverse order.
val filter_in_place : 'a t -> ( 'a -> bool ) -> unitKeep only elements that satisfy the predicate.
CCFQueueFunctional queues
val empty : 'a tval is_empty : 'a t -> boolval singleton : 'a -> 'a tval doubleton : 'a -> 'a -> 'a tSame as take_front, but fails on empty queues.
take_front_l n q takes at most n elements from the front of q, and returns them wrapped in a list.
take_back_l n q removes and returns the last n elements of q. The elements are in the order of the queue, that is, the head of the returned list is the first element to appear via take_front. take_back_l 2 (of_list [1;2;3;4]) = of_list [1;2], [3;4].
val first : 'a t -> 'a optionFirst element of the queue.
val last : 'a t -> 'a optionLast element of the queue.
val last_exn : 'a t -> 'aval nth : int -> 'a t -> 'a optionReturn the i-th element of the queue in logarithmic time.
Append two queues. Elements from the second one come after elements of the first one. Linear in the size of the second queue.
val size : 'a t -> intNumber of elements in the queue (constant time).
val fold : ( 'b -> 'a -> 'b ) -> 'b -> 'a t -> 'bval iter : ( 'a -> unit ) -> 'a t -> unitval of_list : 'a list -> 'a tval to_list : 'a t -> 'a listval to_seq : 'a t -> 'a Stdlib.Seq.tval of_seq : 'a Stdlib.Seq.t -> 'a tval (--) : int -> int -> int ta -- b is the integer range from a to b, both included.
val (--^) : int -> int -> int ta -- b is the integer range from a to b, where b is excluded.
CCFun_vecFunctional Vectors
Tree with a large branching factor for logarithmic operations with a low multiplicative factor.
status: experimental. DO NOT USE (yet)
type 'a ktree = unit -> [ `Nil | `Node of 'a * 'a ktree list ]val empty : 'a tval is_empty : _ t -> boolval return : 'a -> 'a tval length : _ t -> intval get : int -> 'a t -> 'a optionval get_exn : int -> 'a t -> 'aval iter : f:( 'a -> unit ) -> 'a t -> unitval iteri : f:( int -> 'a -> unit ) -> 'a t -> unitIterate on elements with their index, in increasing order.
val iteri_rev : f:( int -> 'a -> unit ) -> 'a t -> unitIterate on elements with their index, but starting from the end.
val fold : f:( 'b -> 'a -> 'b ) -> x:'b -> 'a t -> 'bval foldi : f:( 'b -> int -> 'a -> 'b ) -> x:'b -> 'a t -> 'bval choose : 'a t -> 'a optionval to_list : 'a t -> 'a listval of_list : 'a list -> 'a tCCGraph.Dottype attribute = [ | `Color of string |
| `Shape of string |
| `Weight of int |
| `Style of string |
| `Label of string |
| `Other of string * string |
]Dot attribute
val pp :
+ tbl:( 'v, vertex_state ) table ->
+ eq:( 'v -> 'v -> bool ) ->
+ ?attrs_v:( 'v -> attribute list ) ->
+ ?attrs_e:( 'e -> attribute list ) ->
+ ?name:string ->
+ graph:( 'v, 'e ) t ->
+ Stdlib.Format.formatter ->
+ 'v ->
+ unitPrint the graph, starting from given vertex, on the formatter.
val pp_all :
+ tbl:( 'v, vertex_state ) table ->
+ eq:( 'v -> 'v -> bool ) ->
+ ?attrs_v:( 'v -> attribute list ) ->
+ ?attrs_e:( 'e -> attribute list ) ->
+ ?name:string ->
+ graph:( 'v, 'e ) t ->
+ Stdlib.Format.formatter ->
+ 'v iter ->
+ unitSame as pp but starting from several vertices, not just one.
CCGraph.Itertype 'a t = 'a iterval return : 'a -> 'a tval iter : ( 'a -> unit ) -> 'a t -> unitval fold : ( 'b -> 'a -> 'b ) -> 'b -> 'a t -> 'bval to_list : 'a t -> 'a listCCGraph.Lazy_treeval fold_v : ( 'acc -> 'v -> 'acc ) -> 'acc -> ( 'v, _ ) t -> 'accCCGraph.Mapval empty : 'a tRemove the vertex and all its outgoing edges. Edges that point to the vertex are NOT removed, they must be manually removed with remove_edge.
Traverse.Eventtype ('v, 'e) t = [ | `Enter of 'v * int * ( 'v, 'e ) path |
| `Exit of 'v |
| `Edge of 'v * 'e * 'v * edge_kind |
]A traversal is a sequence of such events
val get_vertex : ( 'v, 'e ) t -> ('v * [ `Enter | `Exit ]) optionval get_enter : ( 'v, 'e ) t -> 'v optionval get_exit : ( 'v, 'e ) t -> 'v optionval get_edge : ( 'v, 'e ) t -> ('v * 'e * 'v) optionCCGraph.TraverseTraversal of the given graph, starting from a sequence of vertices, using the given bag to choose the next vertex to explore. Each vertex is visited at most once.
val generic_tag :
+ tags:'v tag_set ->
+ bag:'v bag ->
+ graph:( 'v, 'e ) t ->
+ 'v iter ->
+ 'v iter_onceOne-shot traversal of the graph using a tag set and the given bag.
val dijkstra :
+ tbl:'v set ->
+ ?dist:( 'e -> int ) ->
+ graph:( 'v, 'e ) t ->
+ 'v iter ->
+ ('v * int * ( 'v, 'e ) path) iter_onceDijkstra algorithm, traverses a graph in increasing distance order. Yields each vertex paired with its distance to the set of initial vertices (the smallest distance needed to reach the node from the initial vertices).
module Event : sig ... endCCGraphSimple Graph Interface
A collections of algorithms on (mostly read-only) graph structures. The user provides her own graph structure as a ('v, 'e) CCGraph.t, where 'v is the type of vertices and 'e the type of edges (for instance, 'e = ('v * 'v) is perfectly fine in many cases).
Such a ('v, 'e) CCGraph.t structure is a record containing three functions: two relate edges to their origin and destination, and one maps vertices to their outgoing edges. This abstract notion of graph makes it possible to run the algorithms on any user-specific type that happens to have a graph structure.
Many graph algorithms here take an iterator of vertices as input. The helper module Iter contains basic functions for that, as does the iter library on opam. If the user only has a single vertex (e.g., for a topological sort from a given vertex), they can use Iter.return x to build a iter of one element.
status: unstable
type 'a iter_once = 'a iterIter that should be used only once
module Iter : sig ... endThis interface is designed for oriented graphs with labels on edges
type ('v, 'e) t = 'v -> ('e * 'v) iterDirected graph with vertices of type 'v and edges labeled with e'
type ('v, 'e) graph = ( 'v, 'e ) tTags
Mutable tags from values of type 'v to tags of type bool
type ('k, 'a) table = {mem : 'k -> bool; | |
find : 'k -> 'a; | (**) |
add : 'k -> 'a -> unit; | (* Erases previous binding *) |
}Table
Mutable table with keys 'k and values 'a
type 'a set = ( 'a, unit ) tableMutable set
val mk_table :
+ eq:( 'k -> 'k -> bool ) ->
+ ?hash:( 'k -> int ) ->
+ int ->
+ ( 'k, 'a ) tableDefault implementation for Table: a Hashtbl.t.
val mk_map : cmp:( 'k -> 'k -> int ) -> unit -> ( 'k, 'a ) tableUse a Map.S underneath.
type 'a bag = {push : 'a -> unit; | |
is_empty : unit -> bool; | |
pop : unit -> 'a; | (* raises some exception is empty *) |
}Bag of elements of type 'a
val mk_queue : unit -> 'a bagval mk_stack : unit -> 'a bagval mk_heap : leq:( 'a -> 'a -> bool ) -> 'a bagmk_heap ~leq makes a priority queue where leq x y = true means that x is smaller than y and should be prioritary.
module Traverse : sig ... endval is_dag :
+ tbl:'v set ->
+ eq:( 'v -> 'v -> bool ) ->
+ graph:( 'v, _ ) t ->
+ 'v iter ->
+ boolis_dag ~graph vs returns true if the subset of graph reachable from vs is acyclic.
val topo_sort :
+ eq:( 'v -> 'v -> bool ) ->
+ ?rev:bool ->
+ tbl:'v set ->
+ graph:( 'v, 'e ) t ->
+ 'v iter ->
+ 'v listtopo_sort ~graph seq returns a list of vertices l where each element of l is reachable from seq. The list is sorted in a way such that if v -> v' in the graph, then v comes before v' in the list (i.e. has a smaller index). Basically v -> v' means that v is smaller than v'. See wikipedia.
val topo_sort_tag :
+ eq:( 'v -> 'v -> bool ) ->
+ ?rev:bool ->
+ tags:'v tag_set ->
+ graph:( 'v, 'e ) t ->
+ 'v iter ->
+ 'v listSame as topo_sort but uses an explicit tag set.
module Lazy_tree : sig ... endval spanning_tree :
+ tbl:'v set ->
+ graph:( 'v, 'e ) t ->
+ 'v ->
+ ( 'v, 'e ) Lazy_tree.tspanning_tree ~graph v computes a lazy spanning tree that has v as a root. The table tbl is used for the memoization part.
val spanning_tree_tag :
+ tags:'v tag_set ->
+ graph:( 'v, 'e ) t ->
+ 'v ->
+ ( 'v, 'e ) Lazy_tree.tHidden state for scc.
val scc :
+ tbl:( 'v, 'v scc_state ) table ->
+ graph:( 'v, 'e ) t ->
+ 'v iter ->
+ 'v list iter_onceStrongly connected components reachable from the given vertices. Each component is a list of vertices that are all mutually reachable in the graph. The components are explored in a topological order (if C1 and C2 are components, and C1 points to C2, then C2 will be yielded before C1). Uses Tarjan's algorithm.
Example (print divisors from 42):
let open CCGraph in
+let open Dot in
+with_out "/tmp/truc.dot"
+ (fun out ->
+ pp ~attrs_v:(fun i -> [`Label (string_of_int i)]) ~graph:divisors_graph out 42
+ )module Dot : sig ... endtype ('v, 'e) mut_graph = {graph : ( 'v, 'e ) t; |
add_edge : 'v -> 'e -> 'v -> unit; |
remove : 'v -> unit; |
}val mk_mut_tbl :
+ eq:( 'v -> 'v -> bool ) ->
+ ?hash:( 'v -> int ) ->
+ int ->
+ ( 'v, 'a ) mut_graphMake a new mutable graph from a Hashtbl. Edges are labelled with type 'a.
A classic implementation of a graph structure on totally ordered vertices, with unlabelled edges. The graph allows to add and remove edges and vertices, and to iterate on edges and vertices.
module type MAP = sig ... endval of_list : eq:( 'v -> 'v -> bool ) -> ('v * 'v) list -> ( 'v, unit ) tof_list l makes a graph from a list of pairs of vertices. Each pair (a,b) is an edge from a to b.
val of_hashtbl : ( 'v, 'v list ) Stdlib.Hashtbl.t -> ( 'v, unit ) tof_hashtbl tbl makes a graph from a hashtable that maps vertices to lists of children.
val of_fun : ( 'v -> 'v list ) -> ( 'v, unit ) tof_fun f makes a graph out of a function that maps a vertex to the list of its children. The function is assumed to be deterministic.
val divisors_graph : ( int, unit ) tn points to all its strict divisors.
CCGraph.MAPval empty : 'a tRemove the vertex and all its outgoing edges. Edges that point to the vertex are NOT removed, they must be manually removed with remove_edge.
Make.1-ECCHashSet.Maketype elt = E.tval create : int -> tcreate n makes a new set with the given capacity n.
val clear : t -> unitclear s removes all elements from s.
val cardinal : t -> intcardinal s returns the number of elements in s.
CCHashSetMutable Set
status: unstable
CCHashSet.ELEMENTCCHashSet.Sval create : int -> tcreate n makes a new set with the given capacity n.
val clear : t -> unitclear s removes all elements from s.
val cardinal : t -> intcardinal s returns the number of elements in s.
Make.1-KCCHashTrie.Maketype key = K.tval empty : 'a tval is_empty : _ t -> boolupdate k ~f m calls f (Some v) if get k m = Some v, f None otherwise. Then, if f returns Some v' it binds k to v', if f returns None it removes k.
val add_mut : id:Transient.t -> key -> 'a -> 'a t -> 'a tadd_mut ~id k v m behaves like add k v m, except it will mutate in place whenever possible. Changes done with an id might affect all versions of the structure obtained with the same id (but not other versions).
val remove_mut : id:Transient.t -> key -> 'a t -> 'a tSame as remove, but modifies in place whenever possible.
val update_mut :
+ id:Transient.t ->
+ key ->
+ f:( 'a option -> 'a option ) ->
+ 'a t ->
+ 'a tSame as update but with mutability.
val cardinal : _ t -> intval add_list_mut : id:Transient.t -> 'a t -> (key * 'a) list -> 'a tval add_iter_mut : id:Transient.t -> 'a t -> (key * 'a) iter -> 'a tval add_gen_mut : id:Transient.t -> 'a t -> (key * 'a) gen -> 'a tCCHashTrie.TransientIdentifiers for transient modifications. A transient modification is uniquely identified by a Transient.t. Once Transient.freeze r is called, r cannot be used to modify the structure again.
val create : unit -> tCreate a new, active ID.
val frozen : t -> boolfrozen i returns true if freeze i was called before. In this case, the ID cannot be used for modifications again.
val active : t -> boolactive i is not (frozen i).
val freeze : t -> unitfreeze i makes i unusable for new modifications. The values created with i will now be immutable.
val with_ : ( t -> 'a ) -> 'awith_ f creates a transient ID i, calls f i, freezes the ID i and returns the result of f i.
CCHashTrieHash Tries
Trie indexed by the hash of the keys, where the branching factor is fixed. The goal is to have a quite efficient functional structure with fast update and access if the hash function is good. The trie is not binary, to improve cache locality and decrease depth.
Preliminary benchmarks (see the "tbl" section of benchmarks) tend to show that this type is quite efficient for small data sets.
status: unstable
type 'a ktree = unit -> [ `Nil | `Node of 'a * 'a ktree list ]module Transient : sig ... endmodule type S = sig ... endmodule type KEY = sig ... endCCHashTrie.KEYCCHashTrie.Sval empty : 'a tval is_empty : _ t -> boolupdate k ~f m calls f (Some v) if get k m = Some v, f None otherwise. Then, if f returns Some v' it binds k to v', if f returns None it removes k.
val add_mut : id:Transient.t -> key -> 'a -> 'a t -> 'a tadd_mut ~id k v m behaves like add k v m, except it will mutate in place whenever possible. Changes done with an id might affect all versions of the structure obtained with the same id (but not other versions).
val remove_mut : id:Transient.t -> key -> 'a t -> 'a tSame as remove, but modifies in place whenever possible.
val update_mut :
+ id:Transient.t ->
+ key ->
+ f:( 'a option -> 'a option ) ->
+ 'a t ->
+ 'a tSame as update but with mutability.
val cardinal : _ t -> intval add_list_mut : id:Transient.t -> 'a t -> (key * 'a) list -> 'a tval add_iter_mut : id:Transient.t -> 'a t -> (key * 'a) iter -> 'a tval add_gen_mut : id:Transient.t -> 'a t -> (key * 'a) gen -> 'a tCCHet.Keyval create : unit -> 'a tCCHet.MapCCHet.TblCCHetAssociative containers with Heterogeneous Values
This is similar to CCMixtbl, but the injection is directly used as a key.
CCImmutArrayImmutable Arrays
Purely functional use of arrays. Update is costly, but reads are very fast. Sadly, it is not possible to make this type covariant without using black magic.
Array of values of type 'a. The underlying type really is an array, but it will never be modified.
It should be covariant but OCaml will not accept it.
val empty : 'a tval length : _ t -> intval singleton : 'a -> 'a tval doubleton : 'a -> 'a -> 'a tval make : int -> 'a -> 'a tmake n x makes an array of n times x.
val init : int -> ( int -> 'a ) -> 'a tinit n f makes the array [| f 0; f 1; ... ; f (n-1) |].
val get : 'a t -> int -> 'aAccess the element.
sub a start len returns a fresh array of length len, containing the elements from start to pstart + len - 1 of array a.
Raises Invalid_argument "Array.sub" if start and len do not designate a valid subarray of a; that is, if start < 0, or len < 0, or start + len > Array.length a.
val iter : ( 'a -> unit ) -> 'a t -> unitval iteri : ( int -> 'a -> unit ) -> 'a t -> unitval foldi : ( 'a -> int -> 'b -> 'a ) -> 'a -> 'b t -> 'aval fold : ( 'a -> 'b -> 'a ) -> 'a -> 'b t -> 'aval for_all : ( 'a -> bool ) -> 'a t -> boolval exists : ( 'a -> bool ) -> 'a t -> boolval of_list : 'a list -> 'a tval to_list : 'a t -> 'a listval of_array_unsafe : 'a array -> 'a tTake ownership of the given array. Careful, the array must NOT be modified afterwards!
val pp :
+ ?pp_start:unit printer ->
+ ?pp_stop:unit printer ->
+ ?pp_sep:unit printer ->
+ 'a printer ->
+ 'a t printerpp ~pp_start ~pp_stop ~pp_sep pp_item ppf a formats the array a on ppf. Each element is formatted with pp_item, pp_start is called at the beginning, pp_stop is called at the end, pp_sep is called between each elements. By defaults pp_start and pp_stop does nothing and pp_sep defaults to (fun out -> Format.fprintf out ",@ ").
CCIntMapMap specialized for Int keys
status: stable
val empty : 'a tval is_empty : _ t -> boolIs the map empty?
val singleton : int -> 'a -> 'a tval doubleton : int -> 'a -> int -> 'a -> 'a tval mem : int -> _ t -> boolval find : int -> 'a t -> 'a optionequal ~eq a b checks whether a and b have the same set of pairs (key, value), comparing values with eq.
Total order between maps; the precise order is unspecified.
Filter-map values using the given function
val cardinal : _ t -> intNumber of bindings in the map. Linear time.
val iter : ( int -> 'a -> unit ) -> 'a t -> unitval fold : ( int -> 'a -> 'b -> 'b ) -> 'a t -> 'b -> 'bval choose : 'a t -> (int * 'a) optionval choose_exn : 'a t -> int * 'aval merge :
+ f:( int -> [ `Left of 'a | `Right of 'b | `Both of 'a * 'b ] -> 'c option ) ->
+ 'a t ->
+ 'b t ->
+ 'c tmerge ~f m1 m2 merges m1 and m2 together, calling f once on every key that occurs in at least one of m1 and m2. if f k binding = Some c then k -> c is part of the result, else k is not part of the result.
val of_list : (int * 'a) list -> 'a tval to_list : 'a t -> (int * 'a) listval of_seq : (int * 'a) Stdlib.Seq.t -> 'a tval to_seq : 'a t -> (int * 'a) Stdlib.Seq.ttype 'a tree = unit -> [ `Nil | `Node of 'a * 'a tree list ]Helpers
CCKTree.Dottype attribute = [ | `Color of string | |
| `Shape of string | |
| `Weight of int | |
| `Style of string | |
| `Label of string | |
| `Id of string | (* Unique ID in the graph. Allows sharing. *) |
| `Other of string * string |
]Dot attributes for nodes
A dot graph is a name, plus a list of trees labelled with attributes
val mk_id : ( 'a, Stdlib.Buffer.t, unit, attribute ) Stdlib.format4 -> 'aUsing a formatter string, build an ID.
val mk_label : ( 'a, Stdlib.Buffer.t, unit, attribute ) Stdlib.format4 -> 'aUsing a formatter string, build a label.
val print_to_file : string -> graph -> unitprint_to_file filename g prints g into a file whose name is filename.
CCKTree.psetAbstract Set structure
method add : 'a -> 'a psetCCKTreeLazy Tree Structure This structure can be used to represent trees and directed graphs (as infinite trees) in a lazy fashion. Like CCKList, it is a structural type.
type +'a t = unit -> [ `Nil | `Node of 'a * 'a t list ]val empty : 'a tval is_empty : _ t -> boolval singleton : 'a -> 'a tTree with only one label.
val fold : ( 'a -> 'b -> 'a ) -> 'a -> 'b t -> 'aFold on values in no specified order. May not terminate if the tree is infinite.
val iter : ( 'a -> unit ) -> 'a t -> unitval size : _ t -> intNumber of elements.
val height : _ t -> intLength of the longest path to empty leaves.
class type 'a pset = object ... endAbstract Set structure
val set_of_cmp : cmp:( 'a -> 'a -> int ) -> unit -> 'a psetBuild a set structure given a total ordering.
Depth-first traversal of the tree.
val force : 'a t -> [ `Nil | `Node of 'a * 'b list ] as 'bforce t evaluates t completely and returns a regular tree structure.
Look for an element that maps to Some _.
Example (tree of calls for naive Fibonacci function):
let mk_fib n =
+ let rec fib' l r i =
+ if i=n then r else fib' r (l+r) (i+1)
+ in fib' 1 1 1;;
+
+let rec fib n = match n with
+ | 0 | 1 -> CCKTree.singleton (`Cst n)
+ | _ -> CCKTree.node2 (`Plus (mk_fib n)) (fib (n-1)) (fib (n-2));;
+
+let pp_node fmt = function
+ | `Cst n -> Format.fprintf fmt "%d" n
+ | `Plus n -> Format.fprintf fmt "%d" n;;
+
+Format.printf "%a@." (CCKTree.pp pp_node) (fib 8);;A pretty-printer using S-expressions and boxes to render the tree. Empty nodes are not rendered; sharing is ignored.
module Dot : sig ... endCCLazy_list.InfixCCLazy_listLazy List
type +'a t = 'a node lazy_tval empty : 'a tEmpty list.
val return : 'a -> 'a tReturn a computed value.
val is_empty : _ t -> boolEvaluate the head.
val length : _ t -> intlength l returns the number of elements in l, eagerly (linear time). Caution, will not terminate if l is infinite.
module Infix : sig ... endval of_list : 'a list -> 'a tval to_list : 'a t -> 'a listval to_list_rev : 'a t -> 'a listMake.1-XCCMixmap.Maketype key = X.tA map containing values of different types, indexed by key.
val empty : tEmpty map.
Get the value corresponding to this key, if it exists and belongs to the same key.
Find the value for the given key, which must be of the right type.
val cardinal : t -> intNumber of bindings.
All the bindings that come from the corresponding injection.
CCMixmapMaps with Heterogeneous Values
status: experimental
module M = CCMixmap.Make(CCInt)
+
+let inj_int = CCMixmap.create_inj()
+let inj_str = CCMixmap.create_inj()
+let inj_list_int = CCMixmap.create_inj()
+
+let m =
+ M.empty
+ |> M.add ~inj:inj_int 1 1
+ |> M.add ~inj:inj_str 2 "2"
+ |> M.add ~inj:inj_list_int 3 [3;3;3]
+
+ assert (M.get ~inj:inj_int 1 m = Some 1)
+ assert (M.get ~inj:inj_str 1 m = None)
+ assert (M.get ~inj:inj_str 2 m = Some "2")
+ assert (M.get ~inj:inj_int 2 m = None)
+ assert (M.get ~inj:inj_list_int 3 m = Some [3;3;3])
+ assert (M.get ~inj:inj_str 3 m = None)change of API, the map is last argument to make piping with |> easier since 0.16.
An accessor for values of type 'a in any map. Values put in the map using a key can only be retrieved using this very same key.
val create_inj : unit -> 'a injectionReturn a value that works for a given type of values. This function is normally called once for each type of value. Several keys may be created for the same type, but a value set with a given setter can only be retrieved with the matching getter. The same key can be reused across multiple maps (although not in a thread-safe way).
module type S = sig ... endmodule type ORD = sig ... endCCMixmap.ORDCCMixmap.SA map containing values of different types, indexed by key.
val empty : tEmpty map.
Get the value corresponding to this key, if it exists and belongs to the same key.
Find the value for the given key, which must be of the right type.
val cardinal : t -> intNumber of bindings.
All the bindings that come from the corresponding injection.
CCMixsetSet of Heterogeneous Values
let k1 : int key = newkey () in
+let k2 : int key = newkey () in
+let k3 : string key = newkey () in
+let set =
+ empty
+ |> set ~key:k1 1
+ |> set ~key:k2 2
+ |> set ~key:k3 "3"
+in
+assert (get ~key:k1 set = Some 1);
+assert (get ~key:k2 set = Some 2);
+assert (get ~key:k3 set = Some "3");
+()val newkey : unit -> 'a keynewkey () creates a new unique key that can be used to access a 'a value in a set. Each key created with newkey is distinct from any other key, even if they have the same type.
Not thread-safe.
val empty : tEmpty set.
set ~key v set maps key to v in set. It means that for every set, get ~key (set ~key v set) = Some v.
val cardinal : t -> intNumber of mappings.
CCMixtblHash Table with Heterogeneous Keys
From https://github.com/mjambon/mixtbl (thanks to him). Example:
let inj_int = CCMixtbl.create_inj () ;;
+
+let tbl = CCMixtbl.create 10 ;;
+
+assert_equal None (CCMixtbl.get ~inj:inj_int tbl "a");;
+
+CCMixtbl.set inj_int tbl "a" 1;;
+
+assert_equal (Some 1) (CCMixtbl.get ~inj:inj_int tbl "a");;
+
+let inj_string = CCMixtbl.create_inj () ;;
+
+CCMixtbl.set inj_string tbl "b" "Hello";
+
+assert_equal (Some "Hello") (CCMixtbl.get inj_string tbl "b");;
+assert_equal None (CCMixtbl.get inj_string tbl "a");;
+assert_equal (Some 1) (CCMixtbl.get inj_int tbl "a");;
+CCMixtbl.set inj_string tbl "a" "Bye";;
+
+assert_equal None (CCMixtbl.get inj_int tbl "a");;
+assert_equal (Some "Bye") (CCMixtbl.get inj_string tbl "a");;A hash table containing values of different types. The type parameter 'a represents the type of the keys.
An accessor for values of type 'b in any table. Values put in the table using a key can only be retrieved using this very same key.
val create : int -> 'a tcreate n creates a hash table of initial size n.
val create_inj : unit -> 'b injectionReturn a value that works for a given type of values. This function is normally called once for each type of value. Several keys may be created for the same type, but a value set with a given setter can only be retrieved with the matching getter. The same key can be reused across multiple tables (although not in a thread-safe way).
Get the value corresponding to this key, if it exists and belongs to the same key.
Find the value for the given key, which must be of the right type.
val length : 'a t -> intNumber of bindings.
val clear : 'a t -> unitClear content of the hashtable.
val remove : 'a t -> 'a -> unitRemove the binding for this key.
val iter_keys : 'a t -> ( 'a -> unit ) -> unitIterate on the keys of this table.
val fold_keys : 'a t -> 'b -> ( 'b -> 'a -> 'b ) -> 'bFold over the keys.
All the bindings that come from the corresponding injection.
Make.1-KMake.2-VCCMultiMap.Makemodule K : OrderedTypemodule V : OrderedTypetype key = K.ttype value = V.tval empty : tEmpty multimap.
val is_empty : t -> boolEmpty multimap?
val size : t -> intNumber of keys.
MakeBidir.1-LMakeBidir.2-RCCMultiMap.MakeBidirmodule L : OrderedTypemodule R : OrderedTypetype left = L.ttype right = R.tval empty : tval is_empty : t -> boolval cardinal_left : t -> intNumber of distinct left keys.
val cardinal_right : t -> intNumber of distinct right keys.
Like find_right but returns at most one value.
CCMultiMapMap that can map key to several values
module type S = sig ... endmodule type OrderedType = sig ... endmodule Make
+ (K : OrderedType)
+ (V : OrderedType) :
+ S with type key = K.t and type value = V.tRepresents n-to-n mappings between two types. Each element from the "left" is mapped to several right values, and conversely.
module type BIDIR = sig ... endmodule MakeBidir
+ (L : OrderedType)
+ (R : OrderedType) :
+ BIDIR with type left = L.t and type right = R.tCCMultiMap.BIDIRval empty : tval is_empty : t -> boolval cardinal_left : t -> intNumber of distinct left keys.
val cardinal_right : t -> intNumber of distinct right keys.
Like find_right but returns at most one value.
CCMultiMap.OrderedTypeCCMultiMap.Sval empty : tEmpty multimap.
val is_empty : t -> boolEmpty multimap?
val size : t -> intNumber of keys.
CCMultiSet.Makeval empty : tval is_empty : t -> boolremove_mult set x n removes at most n occurrences of x from set.
update set x f calls f n where n is the current multiplicity of x in set (0 to indicate its absence); the result of f n is the new multiplicity of x.
union a b contains as many occurrences of an element x as count a x + count b x.
meet a b is a multiset such that count (meet a b) x = max (count a x) (count b x).
intersection a b is a multiset such that count (intersection a b) x = min (count a x) (count b x).
val cardinal : t -> intNumber of distinct elements.
CCMultiSetMultiset
module type S = sig ... endCCMultiSet.Sval empty : tval is_empty : t -> boolremove_mult set x n removes at most n occurrences of x from set.
update set x f calls f n where n is the current multiplicity of x in set (0 to indicate its absence); the result of f n is the new multiplicity of x.
union a b contains as many occurrences of an element x as count a x + count b x.
meet a b is a multiset such that count (meet a b) x = max (count a x) (count b x).
intersection a b is a multiset such that count (intersection a b) x = min (count a x) (count b x).
val cardinal : t -> intNumber of distinct elements.
Make.1-Xval idx : t -> intIndex in heap. return -1 if never set
val set_idx : t -> int -> unitUpdate index in heap
CCMutHeap.Maketype elt = X.tType of elements
val create : unit -> tCreate a heap
val in_heap : elt -> boolval size : t -> intNumber of integers within the heap
val is_empty : t -> boolval clear : t -> unitClear the content of the heap
CCMutHeapMutable Heaps
The classic binary heap in a vector.
STATUS: experimental, this might change in breaking ways.
module type RANKED = CCMutHeap_intf.RANKEDmodule type S = CCMutHeap_intf.SCCMutHeap_intfCCMutHeap_intf.RANKEDval idx : t -> intIndex in heap. return -1 if never set
val set_idx : t -> int -> unitUpdate index in heap
CCMutHeap_intf.Sval create : unit -> tCreate a heap
val in_heap : elt -> boolval size : t -> intNumber of integers within the heap
val is_empty : t -> boolval clear : t -> unitClear the content of the heap
CCPersistentArrayPersistent Arrays
From the paper by Jean-Christophe Filliâtre, "A persistent Union-Find data structure", see the ps version
val make : int -> 'a -> 'a tmake n x returns a persistent array of length n, with x. All the elements of this new array are initially physically equal to x (in the sense of the == predicate). Consequently, if x is mutable, it is shared among all elements of the array, and modifying x through one of the array entries will modify all other entries at the same time.
val init : int -> ( int -> 'a ) -> 'a tinit n f returns a persistent array of length n, with element i initialized to the result of f i.
val get : 'a t -> int -> 'aget a i returns the element with index i from the array a.
val length : 'a t -> intReturn the length of the persistent array.
Apply the given function to all elements of the array, and return a persistent array initialized by the results of f. In the case of mapi, the function is also given the index of the element. It is equivalent to fun f t -> init (fun i -> f (get t i)).
val iter : ( 'a -> unit ) -> 'a t -> unititer f t applies function f to all elements of the persistent array, in order from element 0 to element length t - 1.
val iteri : ( int -> 'a -> unit ) -> 'a t -> unitval fold_left : ( 'a -> 'b -> 'a ) -> 'a -> 'b t -> 'aval fold_right : ( 'a -> 'b -> 'b ) -> 'a t -> 'b -> 'bFold on the elements of the array.
val to_array : 'a t -> 'a arrayto_array t returns a mutable copy of t.
val of_array : 'a array -> 'a tof_array a returns an immutable copy of a.
val to_list : 'a t -> 'a listto_list t returns the list of elements in t.
val of_list : 'a list -> 'a tof_list l returns a fresh persistent array containing the elements of l.
val of_rev_list : 'a list -> 'a tof_rev_list l is the same as of_list (List.rev l) but more efficient.
Make.1-HCCPersistentHashtbl.Makemodule H : HashedTypetype key = H.tval empty : unit -> 'a tEmpty table. The table will be allocated at the first binding.
val create : int -> 'a tCreate a new hashtable, with the given initial capacity.
val is_empty : 'a t -> boolIs the table empty?
val length : _ t -> intNumber of bindings.
Add the binding to the table, returning a new table. The old binding for this key, if it exists, is shadowed and will be restored upon remove tbl k.
Add the binding to the table, returning a new table. This erases the current binding for key, if any.
update tbl key f calls f None if key doesn't belong in tbl, f (Some v) if key -> v otherwise; If f returns None then key is removed, else it returns Some v' and key -> v' is added.
Fresh copy of the table; the underlying structure is not shared anymore, so using both tables alternatively will be efficient.
val merge :
+ f:( key -> [ `Left of 'a | `Right of 'b | `Both of 'a * 'b ] -> 'c option ) ->
+ 'a t ->
+ 'b t ->
+ 'c tMerge two tables together into a new table. The function's argument correspond to values associated with the key (if present); if the function returns None the key will not appear in the result.
val stats : _ t -> Stdlib.Hashtbl.statisticsStatistics on the internal table.
CCPersistentHashtblPersistent hash-table on top of OCaml's hashtables
Almost as efficient as the regular Hashtbl type, but with a persistent interface (rewinding changes to get back in the past history). This is mostly useful for backtracking-like uses, or forward uses (never using old values).
This module is not thread-safe.
module type HashedType = sig ... endmodule type S = sig ... endCCPersistentHashtbl.HashedTypeCCPersistentHashtbl.Sval empty : unit -> 'a tEmpty table. The table will be allocated at the first binding.
val create : int -> 'a tCreate a new hashtable, with the given initial capacity.
val is_empty : 'a t -> boolIs the table empty?
val length : _ t -> intNumber of bindings.
Add the binding to the table, returning a new table. The old binding for this key, if it exists, is shadowed and will be restored upon remove tbl k.
Add the binding to the table, returning a new table. This erases the current binding for key, if any.
update tbl key f calls f None if key doesn't belong in tbl, f (Some v) if key -> v otherwise; If f returns None then key is removed, else it returns Some v' and key -> v' is added.
Fresh copy of the table; the underlying structure is not shared anymore, so using both tables alternatively will be efficient.
val merge :
+ f:( key -> [ `Left of 'a | `Right of 'b | `Both of 'a * 'b ] -> 'c option ) ->
+ 'a t ->
+ 'b t ->
+ 'c tMerge two tables together into a new table. The function's argument correspond to values associated with the key (if present); if the function returns None the key will not appear in the result.
val stats : _ t -> Stdlib.Hashtbl.statisticsStatistics on the internal table.
CCRAL.Infixval (--^) : int -> int -> int ta --^ b is the integer range from a to b, where b is excluded.
CCRALRandom-Access Lists
This is an OCaml implementation of Okasaki's paper "Purely Functional Random Access Lists". It defines a list-like data structure with O(1) cons/tail operations, and O(log(n)) lookup/modification operations.
This module used to be part of containers.misc
status: stable
val empty : 'a tEmpty list.
val is_empty : _ t -> boolCheck whether the list is empty.
val return : 'a -> 'a tSingleton.
val hd : 'a t -> 'aFirst element of the list, or
val length : 'a t -> intNumber of elements. Complexity O(ln n) where n=number of elements.
val get : 'a t -> int -> 'a optionget l i accesses the i-th element of the list. O(log(n)).
get_and_remove_exn l i accesses and removes the i-th element of l.
take_drop n l splits l into a, b such that length a = n if length l >= n, and such that append a b = l.
val iter : f:( 'a -> unit ) -> 'a t -> unitIterate on the list's elements.
val iteri : f:( int -> 'a -> unit ) -> 'a t -> unitval fold : f:( 'b -> 'a -> 'b ) -> x:'b -> 'a t -> 'bFold on the list's elements.
val fold_rev : f:( 'b -> 'a -> 'b ) -> x:'b -> 'a t -> 'bFold on the list's elements, in reverse order (starting from the tail).
val make : int -> 'a -> 'a tval range : int -> int -> int trange i j is i; i+1; ... ; j or j; j-1; ...; i.
val of_list : 'a list -> 'a tConvert a list to a RAL. Caution: non tail-rec.
val to_list : 'a t -> 'a listval of_array : 'a array -> 'a tval to_array : 'a t -> 'a arrayMore efficient than on usual lists.
module Infix : sig ... endArray.ByteEfficient array version for the char type
val dummy : eltA dummy element used for empty slots in the array
val create : int -> tMake an array of the given size, filled with dummy elements.
val length : t -> intlength t gets the total number of elements currently in t.
blit t s arr i len copies len elements from arr starting at i to position s from t.
Make.1-Eltval dummy : tArray.MakeMakes an array given an arbitrary element type
module Elt : sig ... endtype elt = Elt.tThe element type
type t = Elt.t arrayThe type of an array instance
val dummy : eltA dummy element used for empty slots in the array
val create : int -> tMake an array of the given size, filled with dummy elements.
val length : t -> intlength t gets the total number of elements currently in t.
blit t s arr i len copies len elements from arr starting at i to position s from t.
CCRingBuffer.ArrayThe abstract type for arrays
module type S = sig ... endEfficient array version for the char type
Array.Sval dummy : eltA dummy element used for empty slots in the array
val create : int -> tMake an array of the given size, filled with dummy elements.
val length : t -> intlength t gets the total number of elements currently in t.
blit t s arr i len copies len elements from arr starting at i to position s from t.
CCRingBuffer.ByteAn efficient byte based ring buffer
module Array = Array.ByteThe module type of Array for this ring buffer
val create : int -> tcreate size creates a new bounded buffer with given size. The underlying array is allocated immediately and no further (large) allocation will happen from now on.
val capacity : t -> intLength of the inner buffer.
val length : t -> intNumber of elements currently stored in the buffer.
val is_full : t -> booltrue if pushing an element would erase another element.
blit_from buf from_buf o len copies the slice o, ... o + len - 1 from an input buffer from_buf to the end of the buffer. If the slice is too large for the buffer, only the last part of the array will be copied.
blit_into buf to_buf o len copies at most len elements from buf into to_buf starting at offset o in s.
append b ~into copies all data from b and adds it at the end of into. Erases data of into if there is not enough room.
val clear : t -> unitClear the content of the buffer
val is_empty : t -> boolIs the buffer empty (i.e. contains no elements)?
val junk_front : t -> unitDrop the front element from t.
val junk_back : t -> unitDrop the back element from t.
val skip : t -> int -> unitskip b len removes len elements from the front of b.
iteri b ~f calls f i t for each element t in buf, with i being its relative index within buf.
get_front buf i returns the i-th element of buf from the front, i.e. the one returned by take_front buf after i-1 calls to junk_front buf.
get_back buf i returns the i-th element of buf from the back, i.e. the one returned by take_back buf after i-1 calls to junk_back buf.
Push value at the back of t. If t.bounded=false, the buffer will grow as needed, otherwise the oldest elements are replaced first.
Create a buffer from an initial array, but doesn't take ownership of it (still allocates a new internal array).
Make.ArrayThe module type of Array for this ring buffer
type elt = X.tThe element type
type t = X.t arrayThe type of an array instance
val dummy : eltA dummy element used for empty slots in the array
val create : int -> tMake an array of the given size, filled with dummy elements.
val length : t -> intlength t gets the total number of elements currently in t.
blit t s arr i len copies len elements from arr starting at i to position s from t.
Make.1-Xval dummy : tCCRingBuffer.MakeBuffer using regular arrays
module X : sig ... endThe module type of Array for this ring buffer
val create : int -> tcreate size creates a new bounded buffer with given size. The underlying array is allocated immediately and no further (large) allocation will happen from now on.
val capacity : t -> intLength of the inner buffer.
val length : t -> intNumber of elements currently stored in the buffer.
val is_full : t -> booltrue if pushing an element would erase another element.
blit_from buf from_buf o len copies the slice o, ... o + len - 1 from an input buffer from_buf to the end of the buffer. If the slice is too large for the buffer, only the last part of the array will be copied.
blit_into buf to_buf o len copies at most len elements from buf into to_buf starting at offset o in s.
append b ~into copies all data from b and adds it at the end of into. Erases data of into if there is not enough room.
val clear : t -> unitClear the content of the buffer
val is_empty : t -> boolIs the buffer empty (i.e. contains no elements)?
val junk_front : t -> unitDrop the front element from t.
val junk_back : t -> unitDrop the back element from t.
val skip : t -> int -> unitskip b len removes len elements from the front of b.
iteri b ~f calls f i t for each element t in buf, with i being its relative index within buf.
get_front buf i returns the i-th element of buf from the front, i.e. the one returned by take_front buf after i-1 calls to junk_front buf.
get_back buf i returns the i-th element of buf from the back, i.e. the one returned by take_back buf after i-1 calls to junk_back buf.
Push value at the back of t. If t.bounded=false, the buffer will grow as needed, otherwise the oldest elements are replaced first.
Create a buffer from an initial array, but doesn't take ownership of it (still allocates a new internal array).
MakeFromArray.1-Aval dummy : eltA dummy element used for empty slots in the array
val create : int -> tMake an array of the given size, filled with dummy elements.
val length : t -> intlength t gets the total number of elements currently in t.
blit t s arr i len copies len elements from arr starting at i to position s from t.
CCRingBuffer.MakeFromArrayMakes a ring buffer module with the given array type
module Array = AThe module type of Array for this ring buffer
val create : int -> tcreate size creates a new bounded buffer with given size. The underlying array is allocated immediately and no further (large) allocation will happen from now on.
val capacity : t -> intLength of the inner buffer.
val length : t -> intNumber of elements currently stored in the buffer.
val is_full : t -> booltrue if pushing an element would erase another element.
blit_from buf from_buf o len copies the slice o, ... o + len - 1 from an input buffer from_buf to the end of the buffer. If the slice is too large for the buffer, only the last part of the array will be copied.
blit_into buf to_buf o len copies at most len elements from buf into to_buf starting at offset o in s.
append b ~into copies all data from b and adds it at the end of into. Erases data of into if there is not enough room.
val clear : t -> unitClear the content of the buffer
val is_empty : t -> boolIs the buffer empty (i.e. contains no elements)?
val junk_front : t -> unitDrop the front element from t.
val junk_back : t -> unitDrop the back element from t.
val skip : t -> int -> unitskip b len removes len elements from the front of b.
iteri b ~f calls f i t for each element t in buf, with i being its relative index within buf.
get_front buf i returns the i-th element of buf from the front, i.e. the one returned by take_front buf after i-1 calls to junk_front buf.
get_back buf i returns the i-th element of buf from the back, i.e. the one returned by take_back buf after i-1 calls to junk_back buf.
Push value at the back of t. If t.bounded=false, the buffer will grow as needed, otherwise the oldest elements are replaced first.
Create a buffer from an initial array, but doesn't take ownership of it (still allocates a new internal array).
CCRingBufferCircular Buffer (Deque)
Useful for IO, or as a bounded-size alternative to Queue when batch operations are needed.
status: experimental
Change in the API to provide only a bounded buffer since 1.3
module Array : sig ... endThe abstract type for arrays
module type S = sig ... endmodule Byte : S with module Array = Array.ByteAn efficient byte based ring buffer
Makes a ring buffer module with the given array type
S.ArrayThe module type of Array for this ring buffer
val dummy : eltA dummy element used for empty slots in the array
val create : int -> tMake an array of the given size, filled with dummy elements.
val length : t -> intlength t gets the total number of elements currently in t.
blit t s arr i len copies len elements from arr starting at i to position s from t.
CCRingBuffer.SThe abstract ring buffer type, made concrete by choice of ARRAY module implementation
val create : int -> tcreate size creates a new bounded buffer with given size. The underlying array is allocated immediately and no further (large) allocation will happen from now on.
val capacity : t -> intLength of the inner buffer.
val length : t -> intNumber of elements currently stored in the buffer.
val is_full : t -> booltrue if pushing an element would erase another element.
blit_from buf from_buf o len copies the slice o, ... o + len - 1 from an input buffer from_buf to the end of the buffer. If the slice is too large for the buffer, only the last part of the array will be copied.
blit_into buf to_buf o len copies at most len elements from buf into to_buf starting at offset o in s.
append b ~into copies all data from b and adds it at the end of into. Erases data of into if there is not enough room.
val clear : t -> unitClear the content of the buffer
val is_empty : t -> boolIs the buffer empty (i.e. contains no elements)?
val junk_front : t -> unitDrop the front element from t.
val junk_back : t -> unitDrop the back element from t.
val skip : t -> int -> unitskip b len removes len elements from the front of b.
iteri b ~f calls f i t for each element t in buf, with i being its relative index within buf.
get_front buf i returns the i-th element of buf from the front, i.e. the one returned by take_front buf after i-1 calls to junk_front buf.
get_back buf i returns the i-th element of buf from the back, i.e. the one returned by take_back buf after i-1 calls to junk_back buf.
Push value at the back of t. If t.bounded=false, the buffer will grow as needed, otherwise the oldest elements are replaced first.
Create a buffer from an initial array, but doesn't take ownership of it (still allocates a new internal array).
CCSimple_queue.InfixCCSimple_queueFunctional queues (fifo)
Simple implementation of functional queues
val empty : 'a tval is_empty : 'a t -> boolval peek : 'a t -> 'a optionFirst element of the queue.
Append two queues. Elements from the second one come after elements of the first one. Linear in the size of the second queue.
module Infix : sig ... endval length : 'a t -> intNumber of elements in the queue (linear in time).
val fold : ( 'b -> 'a -> 'b ) -> 'b -> 'a t -> 'bval iter : ( 'a -> unit ) -> 'a t -> unitval to_list : 'a t -> 'a listval of_list : 'a list -> 'a tval to_seq : 'a t -> 'a Stdlib.Seq.tRenamed from to_std_seq since 3.0.
val of_seq : 'a Stdlib.Seq.t -> 'a tRenamed from of_std_seq since 3.0.
Make.1-WCCTrie.Maketype char_ = W.char_type key = W.tval empty : 'a tval is_empty : _ t -> boollongest_prefix k m finds the longest prefix of k that leads to at least one path in m (it does not mean that the prefix is bound to a value.
Example: if m has keys "abc0" and "abcd", then longest_prefix "abc2" m will return "abc".
Update the binding for the given key. The function is given None if the key is absent, or Some v if key is bound to v; if it returns None the key is removed, otherwise it returns Some y and key becomes bound to y.
Fold on key/value bindings. Will use WORD.of_list to rebuild keys.
Map values, giving both key and value. Will use WORD.of_list to rebuild keys.
val fold_values : ( 'b -> 'a -> 'b ) -> 'b -> 'a t -> 'bMore efficient version of fold, that doesn't keep keys.
val iter_values : ( 'a -> unit ) -> 'a t -> unitMerge two tries together. The function is used in case of conflicts, when a key belongs to both tries.
val size : _ t -> intNumber of bindings.
All bindings whose key is bigger or equal to the given key, in ascending order.
MakeArray.1-XCCTrie.MakeArraytype char_ = X.ttype key = X.t arrayval empty : 'a tval is_empty : _ t -> boollongest_prefix k m finds the longest prefix of k that leads to at least one path in m (it does not mean that the prefix is bound to a value.
Example: if m has keys "abc0" and "abcd", then longest_prefix "abc2" m will return "abc".
Update the binding for the given key. The function is given None if the key is absent, or Some v if key is bound to v; if it returns None the key is removed, otherwise it returns Some y and key becomes bound to y.
Fold on key/value bindings. Will use WORD.of_list to rebuild keys.
Map values, giving both key and value. Will use WORD.of_list to rebuild keys.
val fold_values : ( 'b -> 'a -> 'b ) -> 'b -> 'a t -> 'bMore efficient version of fold, that doesn't keep keys.
val iter_values : ( 'a -> unit ) -> 'a t -> unitMerge two tries together. The function is used in case of conflicts, when a key belongs to both tries.
val size : _ t -> intNumber of bindings.
All bindings whose key is bigger or equal to the given key, in ascending order.
MakeList.1-XCCTrie.MakeListtype char_ = X.ttype key = X.t listval empty : 'a tval is_empty : _ t -> boollongest_prefix k m finds the longest prefix of k that leads to at least one path in m (it does not mean that the prefix is bound to a value.
Example: if m has keys "abc0" and "abcd", then longest_prefix "abc2" m will return "abc".
Update the binding for the given key. The function is given None if the key is absent, or Some v if key is bound to v; if it returns None the key is removed, otherwise it returns Some y and key becomes bound to y.
Fold on key/value bindings. Will use WORD.of_list to rebuild keys.
Map values, giving both key and value. Will use WORD.of_list to rebuild keys.
val fold_values : ( 'b -> 'a -> 'b ) -> 'b -> 'a t -> 'bMore efficient version of fold, that doesn't keep keys.
val iter_values : ( 'a -> unit ) -> 'a t -> unitMerge two tries together. The function is used in case of conflicts, when a key belongs to both tries.
val size : _ t -> intNumber of bindings.
All bindings whose key is bigger or equal to the given key, in ascending order.
CCTrie.Stringval empty : 'a tval is_empty : _ t -> boollongest_prefix k m finds the longest prefix of k that leads to at least one path in m (it does not mean that the prefix is bound to a value.
Example: if m has keys "abc0" and "abcd", then longest_prefix "abc2" m will return "abc".
Update the binding for the given key. The function is given None if the key is absent, or Some v if key is bound to v; if it returns None the key is removed, otherwise it returns Some y and key becomes bound to y.
Fold on key/value bindings. Will use WORD.of_list to rebuild keys.
Map values, giving both key and value. Will use WORD.of_list to rebuild keys.
val fold_values : ( 'b -> 'a -> 'b ) -> 'b -> 'a t -> 'bMore efficient version of fold, that doesn't keep keys.
val iter_values : ( 'a -> unit ) -> 'a t -> unitMerge two tries together. The function is used in case of conflicts, when a key belongs to both tries.
val size : _ t -> intNumber of bindings.
All bindings whose key is bigger or equal to the given key, in ascending order.
CCTriePrefix Tree
type 'a ktree = unit -> [ `Nil | `Node of 'a * 'a ktree list ]Words are made of characters, who belong to a total order
module type WORD = sig ... endmodule type S = sig ... endmodule type ORDERED = sig ... endCCTrie.ORDEREDCCTrie.Sval empty : 'a tval is_empty : _ t -> boollongest_prefix k m finds the longest prefix of k that leads to at least one path in m (it does not mean that the prefix is bound to a value.
Example: if m has keys "abc0" and "abcd", then longest_prefix "abc2" m will return "abc".
Update the binding for the given key. The function is given None if the key is absent, or Some v if key is bound to v; if it returns None the key is removed, otherwise it returns Some y and key becomes bound to y.
Fold on key/value bindings. Will use WORD.of_list to rebuild keys.
Map values, giving both key and value. Will use WORD.of_list to rebuild keys.
val fold_values : ( 'b -> 'a -> 'b ) -> 'b -> 'a t -> 'bMore efficient version of fold, that doesn't keep keys.
val iter_values : ( 'a -> unit ) -> 'a t -> unitMerge two tries together. The function is used in case of conflicts, when a key belongs to both tries.
val size : _ t -> intNumber of bindings.
All bindings whose key is bigger or equal to the given key, in ascending order.
CCTrie.WORDMake.1-XCCWBTree.Maketype key = X.tval empty : 'a tval is_empty : _ t -> boolnth i m returns the i-th key, value in the ascending order. Complexity is O(log (cardinal m)).
get_rank k m looks for the rank of k in m, i.e. the index of k in the sorted list of bindings of m. let (`At n) = get_rank k m in nth_exn n m = get m k should hold.
update k f m calls f (Some v) if get k m = Some v, f None otherwise. Then, if f returns Some v' it binds k to v', if f returns None it removes k.
val cardinal : _ t -> intval weight : _ t -> intMap values, giving both key and value. Will use WORD.of_list to rebuild keys.
split k t returns l, o, r where l is the part of the map with keys smaller than k, r has keys bigger than k, and o = Some v if k, v belonged to the map.
Like Map.S.merge.
extract_min m returns k, v, m' where k,v is the pair with the smallest key in m, and m' does not contain k.
extract_max m returns k, v, m' where k,v is the pair with the highest key in m, and m' does not contain k.
Randomly choose a (key,value) pair within the tree, using weights as probability weights.
MakeFull.1-XCCWBTree.MakeFullUse the custom X.weight function
type key = X.tval empty : 'a tval is_empty : _ t -> boolnth i m returns the i-th key, value in the ascending order. Complexity is O(log (cardinal m)).
get_rank k m looks for the rank of k in m, i.e. the index of k in the sorted list of bindings of m. let (`At n) = get_rank k m in nth_exn n m = get m k should hold.
update k f m calls f (Some v) if get k m = Some v, f None otherwise. Then, if f returns Some v' it binds k to v', if f returns None it removes k.
val cardinal : _ t -> intval weight : _ t -> intMap values, giving both key and value. Will use WORD.of_list to rebuild keys.
split k t returns l, o, r where l is the part of the map with keys smaller than k, r has keys bigger than k, and o = Some v if k, v belonged to the map.
Like Map.S.merge.
extract_min m returns k, v, m' where k,v is the pair with the smallest key in m, and m' does not contain k.
extract_max m returns k, v, m' where k,v is the pair with the highest key in m, and m' does not contain k.
Randomly choose a (key,value) pair within the tree, using weights as probability weights.
CCWBTreeWeight-Balanced Tree
status: experimental
module type ORD = sig ... endmodule type KEY = sig ... endmodule type S = sig ... endCCWBTree.KEYCCWBTree.ORDCCWBTree.Sval empty : 'a tval is_empty : _ t -> boolnth i m returns the i-th key, value in the ascending order. Complexity is O(log (cardinal m)).
get_rank k m looks for the rank of k in m, i.e. the index of k in the sorted list of bindings of m. let (`At n) = get_rank k m in nth_exn n m = get m k should hold.
update k f m calls f (Some v) if get k m = Some v, f None otherwise. Then, if f returns Some v' it binds k to v', if f returns None it removes k.
val cardinal : _ t -> intval weight : _ t -> intMap values, giving both key and value. Will use WORD.of_list to rebuild keys.
split k t returns l, o, r where l is the part of the map with keys smaller than k, r has keys bigger than k, and o = Some v if k, v belonged to the map.
Like Map.S.merge.
extract_min m returns k, v, m' where k,v is the pair with the smallest key in m, and m' does not contain k.
extract_max m returns k, v, m' where k,v is the pair with the highest key in m, and m' does not contain k.
Randomly choose a (key,value) pair within the tree, using weights as probability weights.
CCZipperList Zipper
The pair l, r represents the list List.rev_append l r, but with the focus on r
val empty : 'a tEmpty zipper.
val is_empty : _ t -> boolEmpty zipper? Returns true iff the two lists are empty.
val to_list : 'a t -> 'a listConvert the zipper back to a list. to_list (l,r) is List.rev_append l r.
val to_rev_list : 'a t -> 'a listConvert the zipper back to a reversed list. In other words, to_list (l,r) is List.rev_append r l.
val make : 'a list -> 'a tCreate a zipper pointing at the first element of the list.
Modify the current element, if any, by returning a new element, or returning None if the element is to be deleted.
Insert an element at the current position. If an element was focused, insert x l adds x just before it, and focuses on x.
val is_focused : _ t -> boolIs the zipper focused on some element? That is, will focused return a Some v?
val focused : 'a t -> 'a optionReturn the focused element, if any. focused zip = Some _ iff empty zip = false.
val focused_exn : 'a t -> 'aReturn the focused element, or
Drop every element on the "right" (calling right then will do nothing), keeping the focused element, if any.
Containers_data_topThis library exposes the following toplevel modules:
CCBV Imperative Bitvectors.CCBijection Functor to build a bijection Represents 1-to-1 mappings between two types. Each element from the "left" is mapped to one "right" value, and conversely.CCBitField Efficient Bit Field for up to 31 or 61 fielsCCCache Caches UtilsCCDeque Imperative dequeCCFQueue Functional queuesCCFun_vec Functional VectorsCCGraph Simple Graph InterfaceCCHashSet Mutable SetCCHashTrie Hash TriesCCHet Associative containers with Heterogeneous ValuesCCImmutArray Immutable ArraysCCIntMap Map specialized for Int keysCCKTree Lazy Tree Structure This structure can be used to represent trees and directed graphs (as infinite trees) in a lazy fashion. Like CCKList, it is a structural type.CCLazy_list Lazy ListCCMixmap Maps with Heterogeneous ValuesCCMixset Set of Heterogeneous ValuesCCMixtbl Hash Table with Heterogeneous KeysCCMultiMap Map that can map key to several valuesCCMultiSet MultisetCCMutHeap Mutable HeapsCCMutHeap_intf CCPersistentArray Persistent ArraysCCPersistentHashtbl Persistent hash-table on top of OCaml's hashtablesCCRAL Random-Access ListsCCRingBuffer Circular Buffer (Deque)CCSimple_queue Functional queues (fifo)CCTrie Prefix TreeCCWBTree Weight-Balanced TreeCCZipper List ZipperThe entry point of this library is the module: Containers_data_top.
CCBlockingQueueThis queue has a limited size. Pushing a value on the queue when it is full will block.
val create : int -> 'a tCreate a new queue of size n. Using n=max_int amounts to using an infinite queue (2^61 items is a lot to fit in memory); using n=1 amounts to using a box with 0 or 1 elements inside.
val push : 'a t -> 'a -> unitpush q x pushes x into q, blocking if the queue is full.
val take : 'a t -> 'aTake the first element, blocking if needed.
val push_list : 'a t -> 'a list -> unitPush items of the list, one by one.
val take_list : 'a t -> int -> 'a listtake_list n q takes n elements out of q.
val try_take : 'a t -> 'a optionTake the first element if the queue is not empty, return None otherwise.
val try_push : 'a t -> 'a -> booltry_push q x pushes x into q if q is not full, in which case it returns true. If it fails because q is full, it returns false.
val peek : 'a t -> 'a optionpeek q returns Some x if x is the first element of q, otherwise it returns None.
val size : _ t -> intNumber of elements currently in the queue.
val capacity : _ t -> intNumber of values the queue can hold.
CCLock.LockRefType allowing to manipulate the lock as a reference.
CCLockA value wrapped into a Mutex, for more safety.
val create : 'a -> 'a tCreate a new protected value.
val with_lock : 'a t -> ( 'a -> 'b ) -> 'bwith_lock l f runs f x where x is the value protected with the lock l, in a critical section. If f x fails, with_lock l f fails too but the lock is released.
val try_with_lock : 'a t -> ( 'a -> 'b ) -> 'b optiontry_with_lock l f runs f x in a critical section if l is not locked. x is the value protected by the lock l. If f x fails, try_with_lock l f fails too but the lock is released.
module LockRef : sig ... endType allowing to manipulate the lock as a reference.
with_lock_as_ref l f calls f with a reference-like object that allows to manipulate the value of l safely. The object passed to f must not escape the function call.
val update : 'a t -> ( 'a -> 'a ) -> unitupdate l f replaces the content x of l with f x, atomically.
val update_map : 'a t -> ( 'a -> 'a * 'b ) -> 'bupdate_map l f computes x', y = f (get l), then puts x' in l and returns y.
val mutex : _ t -> Mutex.tUnderlying mutex.
val get : 'a t -> 'aAtomically get the value in the lock. The value that is returned isn't protected!
val set : 'a t -> 'a -> unitAtomically set the value.
val incr : int t -> unitAtomically increment the value.
val decr : int t -> unitAtomically decrement the value.
val incr_then_get : int t -> intincr_then_get x increments x, and returns its new value.
val get_then_incr : int t -> intget_then_incr x increments x, and returns its previous value.
val decr_then_get : int t -> intdecr_then_get x decrements x, and returns its new value.
val get_then_decr : int t -> intget_then_decr x decrements x, and returns its previous value.
val get_then_set : bool t -> boolget_then_set b sets b to true, and returns the old value.
val get_then_clear : bool t -> boolget_then_clear b sets b to false, and returns the old value.
Fut.InfixMake.FutThe futures are registration points for callbacks, storing a state, that are executed in the pool using run.
type 'a future = 'a tval return : 'a -> 'a tFuture that is already computed.
val fail : exn -> 'a tFuture that fails immediately.
val make : ( unit -> 'a ) -> 'a tCreate a future, representing a value that will be computed by the function. If the function raises, the future will fail.
val make1 : ( 'a -> 'b ) -> 'a -> 'b tval make2 : ( 'a -> 'b -> 'c ) -> 'a -> 'b -> 'c tval get : 'a t -> 'aBlocking get: wait for the future to be evaluated, and get the value, or the exception that failed the future is returned. Raise e if the future failed with e.
val is_done : 'a t -> boolIs the future evaluated (success/failure)?
val on_success : 'a t -> ( 'a -> unit ) -> unitAttach a handler to be called upon success. The handler should not call functions on the future. Might be evaluated now if the future is already done.
val on_failure : _ t -> ( exn -> unit ) -> unitAttach a handler to be called upon failure. The handler should not call any function on the future. Might be evaluated now if the future is already done.
Attach a handler to be called when the future is evaluated. The handler should not call functions on the future. Might be evaluated now if the future is already done.
Wait for the first future to succeed, then launch the second.
Future that waits for all previous futures to terminate. If any future in the array fails, sequence_a l fails too.
map_a f a maps f on every element of a, and will return the array of every result if all calls succeed, or an error otherwise.
Future that waits for all previous futures to terminate. If any future in the list fails, sequence_l l fails too.
map_l f l maps f on every element of l, and will return the list of every result if all calls succeed, or an error otherwise.
Choose among those futures (the first to terminate). Behaves like the first future that terminates, by failing if the future fails.
Choose among those futures (the first to terminate). Behaves like the first future that terminates, by failing if the future fails.
Map the value inside the future, to be computed in a separated job.
Cartesian product of the content of these futures.
app_async f x applies the result of f to the result of x, in a separated job scheduled in the pool.
val sleep : float -> unit tFuture that returns with success in the given amount of seconds. Blocks the thread! If you need to wait on many events, consider using CCTimer.
module Infix : sig ... endinclude module type of InfixMake.1-PCCPool.MakeAfter calling stop (), most functions will raise Stopped. This has the effect of preventing new tasks from being executed.
module Fut : sig ... endCCPoolCCPool.PARAMCCSemaphoreval create : int -> tcreate n creates a semaphore with initial value n.
val get : t -> intCurrent value.
val acquire : int -> t -> unitacquire n s blocks until get s >= n, then atomically sets s := !s - n.
val release : int -> t -> unitrelease n s atomically sets s := !s + n.
val with_acquire : n:int -> t -> f:( unit -> 'a ) -> 'awith_acquire ~n s ~f first acquires s with n units, calls f (), and then releases s with n units. Safely release the semaphore even if f () fails.
val wait_until_at_least : n:int -> t -> f:( unit -> 'a ) -> 'await_until_at_least ~n s ~f waits until get s >= n, then calls f () and returns its result. Doesn't modify the semaphore.
CCThread.Arrval spawn : int -> ( int -> 'a ) -> t arrayArr.spawn n f creates an array res of length n, such that res.(i) = spawn (fun () -> f i).
val join : t array -> unitArr.join a joins every thread in a.
CCThread.Barrierval create : unit -> tCreate a barrier.
val reset : t -> unitReset to initial (non-triggered) state.
val wait : t -> unitwait b waits for barrier b to be activated by activate b. All threads calling this wait until activate b is called. If b is already activated, wait b does nothing.
val activate : t -> unitactivate b unblocks all threads that were waiting on b.
val activated : t -> boolactivated b returns true iff activate b was called, and reset b was not called since. In other words, activated b = true means wait b will not block.
CCThreadstatus: unstable
val spawn : ( unit -> _ ) -> tspawn f creates a new thread that runs f ().
val spawn1 : ( 'a -> _ ) -> 'a -> tspawn1 f x is like spawn (fun () -> f x).
val spawn2 : ( 'a -> 'b -> _ ) -> 'a -> 'b -> tspawn2 f x y is like spawn (fun () -> f x y).
module Arr : sig ... endmodule Barrier : sig ... endCCTimerEvent timer
Used to be part of CCFuture.
val create : unit -> tA new timer.
val set_exn_handler : t -> ( exn -> unit ) -> unitset_exn_handler timer f registers f so that any exception raised by a task scheduled in timer is given to f.
val after : t -> float -> f:( unit -> _ ) -> unitCall the callback f after the given number of seconds.
val at : t -> float -> f:( unit -> _ ) -> unitCreate a future that evaluates to () at the given Unix timestamp.
val every : ?delay:float -> t -> float -> f:( unit -> _ ) -> unitevery timer n ~f calls f () every n seconds. f() can raise ExitEvery to stop the cycle.
val stop : t -> unitStop the given timer, cancelling pending tasks. Idempotent. From now on, calling most other operations on the timer will raise Stopped.
val active : t -> boolReturn true until stop t has been called.
This library exposes the following toplevel modules:
CCBlockingQueue CCLock CCPool CCSemaphore CCThread CCTimer Event timerCCArray.FloatarrayCCArray.Infixval (--) : int -> int -> int tx -- y creates an array containing integers in the range x .. y. Bounds included.
val (--^) : int -> int -> int tx --^ y creates an array containing integers in the range x .. y. Right bound excluded.
CCArrayArray utils
module Floatarray : sig ... endval empty : 'a tempty is the empty array, physically equal to [||].
equal eq a1 a2 is true if the lengths of a1 and a2 are the same and if their corresponding elements test equal, using eq.
compare cmp a1 a2 compares arrays a1 and a2 using the function comparison cmp.
val swap : 'a t -> int -> int -> unitswap a i j swaps elements at indices i and j.
val get_safe : 'a t -> int -> 'a optionget_safe a i returns Some a.(i) if i is a valid index.
val map_inplace : ( 'a -> 'a ) -> 'a t -> unitmap_inplace f a replace all elements of a by its image by f.
val mapi_inplace : ( int -> 'a -> 'a ) -> 'a t -> unitmapi_inplace f a replace all elements of a by its image by f.
val fold : ( 'a -> 'b -> 'a ) -> 'a -> 'b t -> 'afold f init a computes f (… (f (f init a.(0)) a.(1)) …) a.(n-1), where n is the length of the array a. Same as Array.fold_left
val foldi : ( 'a -> int -> 'b -> 'a ) -> 'a -> 'b t -> 'afoldi f init a is just like fold, but it also passes in the index of each element as the second argument to the folded function f.
val fold_while : ( 'a -> 'b -> 'a * [ `Stop | `Continue ] ) -> 'a -> 'b t -> 'afold_while f init a folds left on array a until a stop condition via ('a, `Stop) is indicated by the accumulator.
fold_map f init a is a fold_left-like function, but it also maps the array to another array.
scan_left f init a returns the array [|init; f init x0; f (f init a.(0)) a.(1); …|] .
val reverse_in_place : 'a t -> unitreverse_in_place a reverses the array a in place.
val sorted : ( 'a -> 'a -> int ) -> 'a t -> 'a arraysorted f a makes a copy of a and sorts it with f.
val sort_indices : ( 'a -> 'a -> int ) -> 'a t -> int arraysort_indices f a returns a new array b, with the same length as a, such that b.(i) is the index at which the i-th element of sorted f a appears in a. a is not modified.
In other words, map (fun i -> a.(i)) (sort_indices f a) = sorted f a. sort_indices yields the inverse permutation of sort_ranking.
val sort_ranking : ( 'a -> 'a -> int ) -> 'a t -> int arraysort_ranking f a returns a new array b, with the same length as a, such that b.(i) is the index at which the i-th element of a appears in sorted f a. a is not modified.
In other words, map (fun i -> (sorted f a).(i)) (sort_ranking f a) = a. sort_ranking yields the inverse permutation of sort_indices.
In the absence of duplicate elements in a, we also have lookup_exn a.(i) (sorted a) = (sorted_ranking a).(i).
val mem : ?eq:( 'a -> 'a -> bool ) -> 'a -> 'a t -> boolmem ~eq x a return true if x is present in a. Linear time.
val find_map : ( 'a -> 'b option ) -> 'a t -> 'b optionfind_map f a returns Some y if there is an element x such that f x = Some y. Otherwise returns None.
val find_map_i : ( int -> 'a -> 'b option ) -> 'a t -> 'b optionfind_map_i f a is like find_map, but the index of the element is also passed to the predicate function f.
val find_idx : ( 'a -> bool ) -> 'a t -> (int * 'a) optionfind_idx f a returns Some (i,x) where x is the i-th element of a, and f x holds. Otherwise returns None.
lookup ~cmp key a lookups the index of some key key in a sorted array a. Undefined behavior if the array a is not sorted wrt ~cmp. Complexity: O(log (n)) (dichotomic search).
val bsearch :
+ cmp:( 'a -> 'a -> int ) ->
+ 'a ->
+ 'a t ->
+ [ `All_lower | `All_bigger | `Just_after of int | `Empty | `At of int ]bsearch ~cmp key a finds the index of the object key in the array a, provided a is sorted using cmp. If the array is not sorted, the result is not specified (may raise Invalid_argument).
Complexity: O(log n) where n is the length of the array a (dichotomic search).
for_all2 f [|a1; …; an|] [|b1; …; bn|] is true if each pair of elements ai bi satisfies the predicate f. That is, it returns (f a1 b1) && (f a2 b2) && … && (f an bn).
exists2 f [|a1; …; an|] [|b1; …; bn|] is true if any pair of elements ai bi satisfies the predicate f. That is, it returns (f a1 b1) || (f a2 b2) || … || (f an bn).
fold2 f init a b fold on two arrays a and b stepwise. It computes f (… (f init a1 b1) …) an bn.
val shuffle : 'a t -> unitshuffle a randomly shuffles the array a, in place.
val shuffle_with : Stdlib.Random.State.t -> 'a t -> unitshuffle_with rs a randomly shuffles the array a (like shuffle) but a specialized random state rs is used to control the random numbers being produced during shuffling (for reproducibility).
val random_choose : 'a t -> 'a random_genrandom_choose a rs randomly chooses an element of a.
to_string ~sep item_to_string a print a to a string using sep as a separator between elements of a.
to_iter a returns an iter of the elements of an array a. The input array a is shared with the sequence and modification of it will result in modification of the iterator.
val to_seq : 'a t -> 'a Stdlib.Seq.tto_seq a returns a Seq.t of the elements of an array a. The input array a is shared with the sequence and modification of it will result in modification of the sequence. Renamed from to_std_seq since 3.0.
val pp :
+ ?pp_start:unit printer ->
+ ?pp_stop:unit printer ->
+ ?pp_sep:unit printer ->
+ 'a printer ->
+ 'a t printerpp ~pp_start ~pp_stop ~pp_sep pp_item ppf a formats the array a on ppf. Each element is formatted with pp_item, pp_start is called at the beginning, pp_stop is called at the end, pp_sep is called between each elements. By defaults pp_start and pp_stop does nothing and pp_sep defaults to (fun out -> Format.fprintf out ",@ ").
val pp_i :
+ ?pp_start:unit printer ->
+ ?pp_stop:unit printer ->
+ ?pp_sep:unit printer ->
+ ( int -> 'a printer ) ->
+ 'a t printerpp_i ~pp_start ~pp_stop ~pp_sep pp_item ppf a prints the array a on ppf. The printing function pp_item is giving both index and element. pp_start is called at the beginning, pp_stop is called at the end, pp_sep is called between each elements. By defaults pp_start and pp_stop does nothing and pp_sep defaults to (fun out -> Format.fprintf out ",@ ").
filter f a filters elements out of the array a. Only the elements satisfying the given predicate f will be kept.
filter_map f [|a1; …; an|] calls (f a1) … (f an) and returns an array b consisting of all elements bi such as f ai = Some bi. When f returns None, the corresponding element of a is discarded.
monoid_product f a b passes all combinaisons of tuples from the two arrays a and b to the function f.
flat_map f a transforms each element of a into an array, then flattens.
val except_idx : 'a t -> int -> 'a listexcept_idx a i removes the element of a at given index i, and returns the list of the other elements.
val random : 'a random_gen -> 'a t random_genval random_non_empty : 'a random_gen -> 'a t random_genval random_len : int -> 'a random_gen -> 'a t random_genmodule type MONO_ARRAY = sig ... endval sort_generic :
+ (module MONO_ARRAY with type elt = 'elt and type t = 'arr) ->
+ cmp:( 'elt -> 'elt -> int ) ->
+ 'arr ->
+ unitsort_generic (module M) ~cmp a sorts the array a, without allocating (eats stack space though). Performance might be lower than Array.sort.
It is convenient to openCCArray.Infix to access the infix operators without cluttering the scope too much.
module Infix : sig ... endCCArray.MONO_ARRAYCCArrayLabels.FloatarrayCCArrayLabels.Infixval (--) : int -> int -> int tx -- y creates an array containing integers in the range x .. y. Bounds included.
val (--^) : int -> int -> int tx --^ y creates an array containing integers in the range x .. y. Right bound excluded.
CCArrayLabelsArray utils (Labeled version of CCArray)
module Floatarray : sig ... endval empty : 'a tempty is the empty array, physically equal to [||].
equal eq a1 a2 is true if the lengths of a1 and a2 are the same and if their corresponding elements test equal, using eq.
compare cmp a1 a2 compares arrays a1 and a2 using the function comparison cmp.
val swap : 'a t -> int -> int -> unitswap a i j swaps elements at indices i and j.
val get_safe : 'a t -> int -> 'a optionget_safe a i returns Some a.(i) if i is a valid index.
val map_inplace : f:( 'a -> 'a ) -> 'a t -> unitmap_inplace ~f a replace all elements of a by its image by f.
val mapi_inplace : f:( int -> 'a -> 'a ) -> 'a t -> unitmapi_inplace ~f a replace all elements of a by its image by f.
val fold : f:( 'a -> 'b -> 'a ) -> init:'a -> 'b t -> 'afold ~f ~init a computes f (… (f (f init a.(0)) a.(1)) …) a.(n-1), where n is the length of the array a. Same as ArrayLabels.fold_left
val foldi : f:( 'a -> int -> 'b -> 'a ) -> init:'a -> 'b t -> 'afoldi ~f ~init a is just like fold, but it also passes in the index of each element as the second argument to the folded function f.
val fold_while :
+ f:( 'a -> 'b -> 'a * [ `Stop | `Continue ] ) ->
+ init:'a ->
+ 'b t ->
+ 'afold_while ~f ~init a folds left on array a until a stop condition via ('a, `Stop) is indicated by the accumulator.
fold_map ~f ~init a is a fold_left-like function, but it also maps the array to another array.
scan_left ~f ~init a returns the array [|init; f init x0; f (f init a.(0)) a.(1); …|] .
val reverse_in_place : 'a t -> unitreverse_in_place a reverses the array a in place.
val sorted : f:( 'a -> 'a -> int ) -> 'a t -> 'a arraysorted ~f a makes a copy of a and sorts it with f.
val sort_indices : f:( 'a -> 'a -> int ) -> 'a t -> int arraysort_indices ~f a returns a new array b, with the same length as a, such that b.(i) is the index at which the i-th element of sorted f a appears in a. a is not modified.
In other words, map (fun i -> a.(i)) (sort_indices f a) = sorted f a. sort_indices yields the inverse permutation of sort_ranking.
val sort_ranking : f:( 'a -> 'a -> int ) -> 'a t -> int arraysort_ranking ~f a returns a new array b, with the same length as a, such that b.(i) is the index at which the i-th element of a appears in sorted f a. a is not modified.
In other words, map (fun i -> (sorted f a).(i)) (sort_ranking f a) = a. sort_ranking yields the inverse permutation of sort_indices.
In the absence of duplicate elements in a, we also have lookup_exn a.(i) (sorted a) = (sorted_ranking a).(i).
val mem : ?eq:( 'a -> 'a -> bool ) -> 'a -> 'a t -> boolmem ~eq x a return true if x is present in a. Linear time.
val find_map : f:( 'a -> 'b option ) -> 'a t -> 'b optionfind_map ~f a returns Some y if there is an element x such that f x = Some y. Otherwise returns None.
val find_map_i : f:( int -> 'a -> 'b option ) -> 'a t -> 'b optionfind_map_i ~f a is like find_map, but the index of the element is also passed to the predicate function f.
val find_idx : f:( 'a -> bool ) -> 'a t -> (int * 'a) optionfind_idx ~f a returns Some (i,x) where x is the i-th element of a, and f x holds. Otherwise returns None.
lookup ~cmp ~key a lookups the index of some key key in a sorted array a. Undefined behavior if the array a is not sorted wrt cmp. Complexity: O(log (n)) (dichotomic search).
val bsearch :
+ cmp:( 'a -> 'a -> int ) ->
+ key:'a ->
+ 'a t ->
+ [ `All_lower | `All_bigger | `Just_after of int | `Empty | `At of int ]bsearch ~cmp ~key a finds the index of the object key in the array a, provided a is sorted using cmp. If the array is not sorted, the result is not specified (may raise Invalid_argument).
Complexity: O(log n) where n is the length of the array a (dichotomic search).
for_all2 ~f [|a1; …; an|] [|b1; …; bn|] is true if each pair of elements ai bi satisfies the predicate f. That is, it returns (f a1 b1) && (f a2 b2) && … && (f an bn).
exists2 ~f [|a1; …; an|] [|b1; …; bn|] is true if any pair of elements ai bi satisfies the predicate f. That is, it returns (f a1 b1) || (f a2 b2) || … || (f an bn).
fold2 ~f ~init a b fold on two arrays a and b stepwise. It computes f (… (f init a1 b1) …) an bn.
iter2 ~f a b iterates on the two arrays a and b stepwise. It is equivalent to f a0 b0; …; f a.(length a - 1) b.(length b - 1); ().
val shuffle : 'a t -> unitshuffle a randomly shuffles the array a, in place.
val shuffle_with : Stdlib.Random.State.t -> 'a t -> unitshuffle_with rs a randomly shuffles the array a (like shuffle) but a specialized random state rs is used to control the random numbers being produced during shuffling (for reproducibility).
val random_choose : 'a t -> 'a random_genrandom_choose a rs randomly chooses an element of a.
to_string ~sep item_to_string a print a to a string using sep as a separator between elements of a.
to_iter a returns an iter of the elements of an array a. The input array a is shared with the sequence and modification of it will result in modification of the iterator.
val to_seq : 'a t -> 'a Stdlib.Seq.tto_seq a returns a Seq.t of the elements of an array a. The input array a is shared with the sequence and modification of it will result in modification of the sequence. Renamed from to_std_seq since 3.0.
val pp :
+ ?pp_start:unit printer ->
+ ?pp_stop:unit printer ->
+ ?pp_sep:unit printer ->
+ 'a printer ->
+ 'a t printerpp ~pp_start ~pp_stop ~pp_sep pp_item ppf a formats the array a on ppf. Each element is formatted with pp_item, pp_start is called at the beginning, pp_stop is called at the end, pp_sep is called between each elements. By defaults pp_start and pp_stop does nothing and pp_sep defaults to (fun out -> Format.fprintf out ",@ ").
val pp_i :
+ ?pp_start:unit printer ->
+ ?pp_stop:unit printer ->
+ ?pp_sep:unit printer ->
+ ( int -> 'a printer ) ->
+ 'a t printerpp_i ~pp_start ~pp_stop ~pp_sep pp_item ppf a prints the array a on ppf. The printing function pp_item is giving both index and element. pp_start is called at the beginning, pp_stop is called at the end, pp_sep is called between each elements. By defaults pp_start and pp_stop does nothing and pp_sep defaults to (fun out -> Format.fprintf out ",@ ").
map2 ~f a b applies function f to all elements of a and b, and builds an array with the results returned by f: [| f a.(0) b.(0); …; f a.(length a - 1) b.(length b - 1)|].
filter ~f a filters elements out of the array a. Only the elements satisfying the given predicate f will be kept.
filter_map ~f [|a1; …; an|] calls (f a1) … (f an) and returns an array b consisting of all elements bi such as f ai = Some bi. When f returns None, the corresponding element of a is discarded.
monoid_product ~f a b passes all combinaisons of tuples from the two arrays a and b to the function f.
flat_map ~f a transforms each element of a into an array, then flattens.
val except_idx : 'a t -> int -> 'a listexcept_idx a i removes the element of a at given index i, and returns the list of the other elements.
val random : 'a random_gen -> 'a t random_genval random_non_empty : 'a random_gen -> 'a t random_genval random_len : int -> 'a random_gen -> 'a t random_genmodule type MONO_ARRAY = sig ... endval sort_generic :
+ (module MONO_ARRAY with type elt = 'elt and type t = 'arr) ->
+ cmp:( 'elt -> 'elt -> int ) ->
+ 'arr ->
+ unitsort_generic (module M) ~cmp a sorts the array a, without allocating (eats stack space though). Performance might be lower than Array.sort.
It is convenient to openCCArray.Infix to access the infix operators without cluttering the scope too much.
module Infix : sig ... endCCArrayLabels.MONO_ARRAYCCAtomicCCBoolBasic Bool functions
compare b1 b2 is the total ordering on booleans b1 and b2, similar to Stdlib.compare.
val to_int : t -> intto_int true = 1, to_int false = 0.
val of_int : int -> tof_int i is the same as i <> 0
CCByte_bufferByte buffer.
A dynamic vector of bytes.
val create : ?cap:int -> unit -> tCreate a new buffer with given initial capacity.
val length : t -> intCurrent length.
val is_empty : t -> boolis_empty b is length b=0
val bytes : t -> bytesAccess the underlying byte buffer. This buffer can change after operations that affect the capacity (e.g. add_char).
val clear : t -> unitval ensure_cap : t -> int -> unitensure_cap self n ensures that capacity self >= n.
val shrink_to : t -> int -> unitshrink_to buf n reduces length buf to at most n. Does nothing if the length is already <= n.
val add_char : t -> char -> unitPush a character at the end.
val append_bytes : t -> bytes -> unitval append_subbytes : t -> bytes -> int -> int -> unitval append_string : t -> string -> unitval append_substring : t -> string -> int -> int -> unitval append_buf : t -> Stdlib.Buffer.t -> unitval append_seq : t -> char Stdlib.Seq.t -> unitval get : t -> int -> charval unsafe_get : t -> int -> charval set : t -> int -> char -> unitval unsafe_set : t -> int -> char -> unitval contents : t -> stringCopy the internal data to a string
val contents_bytes : t -> bytesCopy the internal data to a byte buffer
val iter : ( char -> unit ) -> t -> unitval fold_left : ( 'a -> char -> 'a ) -> 'a -> t -> 'aval of_seq : char Stdlib.Seq.t -> tval to_seq : t -> char Stdlib.Seq.tMake.1-Sexpval atom : string -> tCCCanonical_sexp.Maketype t = Sexp.ttype sexp = tval atom : string -> tMake an atom out of this string.
val of_int : int -> tval of_bool : bool -> tval of_float : float -> tval of_unit : tof_variant name args is used to encode algebraic variants into a S-expr. For instance of_variant "some" [of_int 1] represents the value Some 1.
val to_buf : Stdlib.Buffer.t -> t -> unitval to_string : t -> stringval to_file : string -> t -> unitval to_file_iter : string -> t CCSexp_intf.iter -> unitPrint the given iter of expressions to a file.
val to_chan : Stdlib.out_channel -> t -> unitval pp : Stdlib.Format.formatter -> t -> unitPretty-printer nice on human eyes (including indentation).
val pp_noindent : Stdlib.Format.formatter -> t -> unitRaw, direct printing as compact as possible.
val parse_string : string -> t CCSexp_intf.or_errorParse a string.
val parse_string_list : string -> t list CCSexp_intf.or_errorParse a string into a list of S-exprs.
val parse_chan : Stdlib.in_channel -> t CCSexp_intf.or_errorParse a S-expression from the given channel. Can read more data than necessary, so don't use this if you need finer-grained control (e.g. to read something else after the S-exp).
val parse_chan_gen :
+ Stdlib.in_channel ->
+ t CCSexp_intf.or_error CCSexp_intf.genParse a channel into a generator of S-expressions.
val parse_chan_list : Stdlib.in_channel -> t list CCSexp_intf.or_errorval parse_file : string -> t CCSexp_intf.or_errorOpen the file and read a S-exp from it.
val parse_file_list : string -> t list CCSexp_intf.or_errorOpen the file and read a S-exp from it.
CCCanonical_sexpCanonical S-expressions
See wikipedia. These S-expressions are binary safe.
module type SEXP = CCSexp_intf.BASIC_SEXPmodule type S = CCSexp_intf.S0A simple, structural representation of S-expressions. Compatible with CCSexp.
include S with type t := ttype sexp = tval of_int : int -> tval of_bool : bool -> tval of_float : float -> tval of_unit : tof_variant name args is used to encode algebraic variants into a S-expr. For instance of_variant "some" [of_int 1] represents the value Some 1.
val to_buf : Stdlib.Buffer.t -> t -> unitval to_string : t -> stringval to_file : string -> t -> unitval to_file_iter : string -> t CCSexp_intf.iter -> unitPrint the given iter of expressions to a file.
val to_chan : Stdlib.out_channel -> t -> unitval pp : Stdlib.Format.formatter -> t -> unitPretty-printer nice on human eyes (including indentation).
val pp_noindent : Stdlib.Format.formatter -> t -> unitRaw, direct printing as compact as possible.
val parse_string : string -> t CCSexp_intf.or_errorParse a string.
val parse_string_list : string -> t list CCSexp_intf.or_errorParse a string into a list of S-exprs.
val parse_chan : Stdlib.in_channel -> t CCSexp_intf.or_errorParse a S-expression from the given channel. Can read more data than necessary, so don't use this if you need finer-grained control (e.g. to read something else after the S-exp).
val parse_chan_gen :
+ Stdlib.in_channel ->
+ t CCSexp_intf.or_error CCSexp_intf.genParse a channel into a generator of S-expressions.
val parse_chan_list : Stdlib.in_channel -> t list CCSexp_intf.or_errorval parse_file : string -> t CCSexp_intf.or_errorOpen the file and read a S-exp from it.
val parse_file_list : string -> t list CCSexp_intf.or_errorOpen the file and read a S-exp from it.
val atom : string -> tCCChar.InfixCCCharUtils around char
include module type of struct include Stdlib.Char endThe comparison function for characters, with the same specification as Stdlib.compare. Along with the type t, this function compare allows the module Char to be passed as argument to the functors Set.Make and Map.Make.
val of_int_exn : int -> tAlias to Char.chr. Return the character with the given ASCII code.
val of_int : int -> t optionSafe version of of_int_exn.
val to_int : t -> intAlias to Char.code. Return the ASCII code of the argument.
val to_string : t -> stringto_string c returns a string containing c
val pp_buf : Stdlib.Buffer.t -> t -> unitRenamed from pp since 2.0.
val pp : Stdlib.Format.formatter -> t -> unitRenamed from print since 2.0.
module Infix : sig ... endCCEitherEither Monad
Module that is compatible with Either form OCaml 4.12 but can be use with any ocaml version compatible with container
val left : 'a -> ( 'a, 'b ) tleft l is Left l
val right : 'b -> ( 'a, 'b ) tright r is Right r
val is_left : ( 'a, 'b ) t -> boolis_left x checks if x = Left _
val is_right : ( 'a, 'b ) t -> boolis_right x checks if x = Right _
val find_left : ( 'a, 'b ) t -> 'a optionfind_left x returns l if x = Left l and None otherwise.
val find_right : ( 'a, 'b ) t -> 'b optionfind_right x returns r if x = Left r and None otherwise.
Map using left or right.
val fold : left:( 'a -> 'c ) -> right:( 'b -> 'c ) -> ( 'a, 'b ) t -> 'cFold using left or right.
val iter : left:( 'a -> unit ) -> right:( 'b -> unit ) -> ( 'a, 'b ) t -> unitIter using left or right.
val for_all :
+ left:( 'a -> bool ) ->
+ right:( 'b -> bool ) ->
+ ( 'a, 'b ) t ->
+ boolCheck some property on Left or Right variant.
CCEqual.InfixCCEqualEquality Combinators
val poly : 'a tStandard polymorphic equality.
val physical : 'a tStandard physical equality.
val int : int tval string : string tval bool : bool tval float : float tval unit : unit tmap f eq is the equality function that, given objects x and y, projects x and y using f (e.g. using a record field) and then compares those projections with eq. Example: map fst int compares values of type (int * 'a) by their first component.
val always_eq : _ tAlways returns true. All values are equal.
val never_eq : _ tAlways returns false. No values are, so this is not even reflexive (i.e. x=x is false). Be careful!
module Infix : sig ... endCCEqualLabels.InfixCCEqualLabelsEquality Combinators (Labeled version of CCEqual)
val poly : 'a tStandard polymorphic equality.
val physical : 'a tStandard physical equality.
val int : int tval string : string tval bool : bool tval float : float tval unit : unit tmap f eq is the equality function that, given objects x and y, projects x and y using f (e.g. using a record field) and then compares those projections with eq. Example: map fst int compares values of type (int * 'a) by their first component.
val always_eq : _ tAlways returns true. All values are equal.
val never_eq : _ tAlways returns false. No values are, so this is not even reflexive (i.e. x=x is false). Be careful!
module Infix : sig ... endCCFloat.InfixCCFloatBasic operations on floating-point numbers
val nan : tnan is Not a Number (NaN). Equal to Stdlib.nan.
val max_value : tmax_value is Positive infinity. Equal to Stdlib.infinity.
val min_value : tmin_value is Negative infinity. Equal to Stdlib.neg_infinity.
val max_finite_value : tmax_finite_value is the largest finite float value. Equal to Stdlib.max_float.
val epsilon : tepsilon is the smallest positive float x such that 1.0 +. x <> 1.0. Equal to Stdlib.epsilon_float.
val pi : tpi is the constant pi. The ratio of a circumference to its diameter.
val is_nan : t -> boolis_nan f returns true if f is NaN, false otherwise.
abs x is the absolute value of the floating-point number x. Equal to Stdlib.abs_float.
val hash : t -> intval random : t -> t random_genval random_small : t random_genval random_range : t -> t -> t random_genround x returns the closest integer value, either above or below. For n + 0.5, round returns n.
val sign_exn : t -> intsign_exn x will return the sign of x as 1, 0 or -1, or raise an exception TrapNaN if x is NaN. Note that infinities have defined signs in OCaml.
val to_int : t -> intAlias to int_of_float. Unspecified if outside of the range of integers.
val of_int : int -> tAlias to float_of_int.
val to_string : t -> stringval of_string_exn : string -> tAlias to float_of_string.
val of_string_opt : string -> t optionEquality with allowed error up to a non negative epsilon value.
classify x returns the class of the given floating-point number x: normal, subnormal, zero, infinite or nan (not a number).
module Infix : sig ... endinclude module type of InfixCCFormat.ANSI_codesANSI escape codes. This contains lower level functions for them.
A style. Styles can be composed in a list.
clear_line is an escape code to clear the current line. It is very useful for progress bars; for example:
let pp_progress i =
+ Printf.printf "%sprogress at %d%!" ANSI_codes.clear_line iif called repeatedly this will print successive progress messages on a single line.
val string_of_style : style -> stringstring_of_style st is an escape code to set the current style to st. It can be printed as is on any output that is a compatible terminal.
val string_of_style_list : style list -> stringstring_of_style_list styles is an escape code for multiple styles at once. For example string_of_style_list ANSI_codes.([`FG `Red; `BG `Green; `Bold]) is a very shiny style.
CCFormat.Dumptype 'a t = 'a printerval unit : unit tval int : int tval string : string tval bool : bool tval float : float tval char : char tval int32 : int32 tval int64 : int64 tval nativeint : nativeint tval to_string : 'a t -> 'a -> stringAlias to CCFormat.to_string.
CCFormat.InfixCCFormatHelpers for Format
include module type of struct include Stdlib.Format endval pp_open_box : formatter -> int -> unitval pp_close_box : formatter -> unit -> unitval pp_open_hbox : formatter -> unit -> unitval pp_open_vbox : formatter -> int -> unitval pp_open_hvbox : formatter -> int -> unitval pp_open_hovbox : formatter -> int -> unitval pp_print_string : formatter -> string -> unitval pp_print_bytes : formatter -> bytes -> unitval pp_print_as : formatter -> int -> string -> unitval pp_print_int : formatter -> int -> unitval pp_print_float : formatter -> float -> unitval pp_print_char : formatter -> char -> unitval pp_print_bool : formatter -> bool -> unitval pp_print_space : formatter -> unit -> unitval pp_print_cut : formatter -> unit -> unitval pp_print_break : formatter -> int -> int -> unitval pp_print_custom_break :
+ formatter ->
+ fits:(string * int * string) ->
+ breaks:(string * int * string) ->
+ unitval pp_force_newline : formatter -> unit -> unitval pp_print_if_newline : formatter -> unit -> unitval pp_print_flush : formatter -> unit -> unitval pp_print_newline : formatter -> unit -> unitval pp_set_margin : formatter -> int -> unitval pp_get_margin : formatter -> unit -> intval pp_set_max_indent : formatter -> int -> unitval pp_get_max_indent : formatter -> unit -> intval check_geometry : geometry -> boolval pp_set_geometry : formatter -> max_indent:int -> margin:int -> unitval pp_safe_set_geometry : formatter -> max_indent:int -> margin:int -> unitval get_geometry : unit -> geometryval pp_set_max_boxes : formatter -> int -> unitval pp_get_max_boxes : formatter -> unit -> intval pp_over_max_boxes : formatter -> unit -> boolval pp_open_tbox : formatter -> unit -> unitval pp_close_tbox : formatter -> unit -> unitval pp_set_tab : formatter -> unit -> unitval pp_print_tab : formatter -> unit -> unitval pp_print_tbreak : formatter -> int -> int -> unitval pp_set_ellipsis_text : formatter -> string -> unitval pp_get_ellipsis_text : formatter -> unit -> stringval open_stag : stag -> unitval pp_close_stag : formatter -> unit -> unitval pp_set_tags : formatter -> bool -> unitval pp_set_print_tags : formatter -> bool -> unitval pp_set_mark_tags : formatter -> bool -> unitval pp_get_print_tags : formatter -> unit -> boolval pp_get_mark_tags : formatter -> unit -> boolval pp_set_formatter_out_channel : formatter -> Stdlib.out_channel -> unitval pp_set_formatter_output_functions :
+ formatter ->
+ ( string -> int -> int -> unit ) ->
+ ( unit -> unit ) ->
+ unitval pp_get_formatter_output_functions :
+ formatter ->
+ unit ->
+ ( string -> int -> int -> unit ) * ( unit -> unit )val pp_set_formatter_out_functions :
+ formatter ->
+ formatter_out_functions ->
+ unitval set_formatter_out_functions : formatter_out_functions -> unitval pp_get_formatter_out_functions :
+ formatter ->
+ unit ->
+ formatter_out_functionsval get_formatter_out_functions : unit -> formatter_out_functionsval pp_set_formatter_stag_functions :
+ formatter ->
+ formatter_stag_functions ->
+ unitval set_formatter_stag_functions : formatter_stag_functions -> unitval pp_get_formatter_stag_functions :
+ formatter ->
+ unit ->
+ formatter_stag_functionsval get_formatter_stag_functions : unit -> formatter_stag_functionsval formatter_of_out_channel : Stdlib.out_channel -> formatterval std_formatter : formatterval err_formatter : formatterval formatter_of_buffer : Stdlib.Buffer.t -> formatterval str_formatter : formatterval make_formatter :
+ ( string -> int -> int -> unit ) ->
+ ( unit -> unit ) ->
+ formatterval formatter_of_out_functions : formatter_out_functions -> formatterval make_symbolic_output_buffer : unit -> symbolic_output_bufferval clear_symbolic_output_buffer : symbolic_output_buffer -> unitval get_symbolic_output_buffer :
+ symbolic_output_buffer ->
+ symbolic_output_item listval flush_symbolic_output_buffer :
+ symbolic_output_buffer ->
+ symbolic_output_item listval add_symbolic_output_item :
+ symbolic_output_buffer ->
+ symbolic_output_item ->
+ unitval formatter_of_symbolic_output_buffer : symbolic_output_buffer -> formatterval pp_print_text : formatter -> string -> unitval printf : ( 'a, formatter, unit ) Stdlib.format -> 'aval eprintf : ( 'a, formatter, unit ) Stdlib.format -> 'aval asprintf : ( 'a, formatter, unit, string ) Stdlib.format4 -> 'aval kasprintf :
+ ( string -> 'a ) ->
+ ( 'b, formatter, unit, 'a ) Stdlib.format4 ->
+ 'bval bprintf : Stdlib.Buffer.t -> ( 'a, formatter, unit ) Stdlib.format -> 'aval pp_set_all_formatter_output_functions :
+ formatter ->
+ out:( string -> int -> int -> unit ) ->
+ flush:( unit -> unit ) ->
+ newline:( unit -> unit ) ->
+ spaces:( int -> unit ) ->
+ unitval pp_get_all_formatter_output_functions :
+ formatter ->
+ unit ->
+ ( string ->
+ int ->
+ int ->
+ unit )
+ * ( unit ->
+ unit )
+ * ( unit ->
+ unit )
+ * ( int ->
+ unit )val open_tag : tag -> unitval pp_close_tag : formatter -> unit -> unitval pp_set_formatter_tag_functions :
+ formatter ->
+ formatter_tag_functions ->
+ unitval set_formatter_tag_functions : formatter_tag_functions -> unitval pp_get_formatter_tag_functions :
+ formatter ->
+ unit ->
+ formatter_tag_functionsval get_formatter_tag_functions : unit -> formatter_tag_functionstype -'a printer = t -> 'a -> unitval silent : 'a printerPrints nothing.
val unit : unit printerPrints "()".
val int : int printerval string : string printerval bool : bool printerval float3 : float printerval float : float printerval exn : exn printerPrinter using Printexc.to_string.
val space : unit printerAlias to pp_print_space.
val cut : unit printerAlias to pp_print_cut.
val break : (int * int) printerTuple-ized printer form of pp_print_break.
val newline : unit printerForce newline (see Format.pp_force_newline).
val substring : (string * int * int) printersubstring (s,i,len) prints the substring (s,i,len), where i is the offset in s and len the number of bytes in the substring.
val text : string printerPrint string, but replacing spaces with breaks and newlines with newline. See pp_print_text on recent versions of OCaml.
val string_lines : string printerstring_lines out s prints s with all newlines ('\n') replaced by a cut, in a vertical box. It does NOT insert breakable spaces in place of spaces, unlike text. This means an already formatted string can be displayed inside another formatter without mangling the indentation.
val char : char printerval int32 : int32 printerval int64 : int64 printerval nativeint : nativeint printerval flush : unit printerAlias to Format.pp_print_flush.
val string_quoted : string printerSimilar to CCString.print.
opt pp prints options as follows:
Some x will become "some foo" if pp x ---> "foo".None will become "none".In the tuple printers, the sep argument is only available.
append ppa ppb first prints ppa (), then prints ppb ().
within a b p wraps p inside the strings a and b. Convenient, for instances, for brackets, parenthesis, quotes, etc.
val return : ( 'a, _, _, 'a ) Stdlib.format4 -> unit printerreturn "some_format_string" takes a argument-less format string and returns a printer actionable by (). Examples:
return ",@ "return "@{<Red>and then@}@,"return "@[<v>a@ b@]"val of_to_string : ( 'a -> string ) -> 'a printerof_to_string f converts its input to a string using f, then prints the string.
some pp will print options as follows:
Some x is printed using pp on xNone is not printed at allval const_string : string -> 'a printerconst_string s is a printer that ignores its input and always prints s.
val opaque : 'a printeropaque is const_string "opaque". The exact string used is not stable.
lazy_force pp out x forces x and prints the result with pp.
lazy_or ?default pp out x prints default if x is not evaluated yet, or uses pp otherwise.
Use ANSI escape codes https://en.wikipedia.org/wiki/ANSI_escape_code to put some colors on the terminal.
This uses tags in format strings to specify the style. Current styles are the following:
Example:
set_color_default true;;
+
+Format.printf
+ "what is your @{<White>favorite color@}? @{<blue>blue@}! No, @{<red>red@}! Ahhhhhhh@.";;status: unstable
val set_color_tag_handling : t -> unitAdd functions to support color tags to the given formatter.
set_color_default b enables color handling on the standard formatters (stdout, stderr) if b = true as well as on sprintf formatters; it disables the color handling if b = false.
with_color "Blue" pp behaves like the printer pp, but with the given style.
status: unstable
with_colorf "Blue" out "%s %d" "yolo" 42 will behave like Format.fprintf, but wrapping the content with the given style.
status: unstable
val with_color_sf : string -> ( 'a, t, unit, string ) Stdlib.format4 -> 'awith_color_sf "Blue" out "%s %d" "yolo" 42 will behave like sprintf, but wrapping the content with the given style.
Example:
CCFormat.with_color_sf "red" "%a" CCFormat.Dump.(list int) [1;2;3] |> print_endline;;status: unstable
val with_color_ksf :
+ f:( string -> 'b ) ->
+ string ->
+ ( 'a, t, unit, 'b ) Stdlib.format4 ->
+ 'awith_color_ksf "Blue" ~f "%s %d" "yolo" 42 will behave like ksprintf, but wrapping the content with the given style.
Example: the following with raise Failure with a colored message
CCFormat.with_color_ksf "red" ~f:failwith "%a" CCFormat.Dump.(list int) [1;2;3];;module ANSI_codes : sig ... endANSI escape codes. This contains lower level functions for them.
val styling : ANSI_codes.style list -> 'a printer -> 'a printerstyling st p is the same printer as p, except it locally sets the style st.
Example:
open CCFormat;
+set_color_default true;
+sprintf
+ "what is your %a? %a! No, %a! Ahhhhhhh@."
+ (styling [`FG `White; `Bold] string) "favorite color"
+ (styling [`FG `Blue] string) "blue"
+ (styling [`FG `Red] string) "red"Available only on OCaml >= 4.08.
val with_styling : ANSI_codes.style list -> t -> ( unit -> 'a ) -> 'awith_styling style fmt f sets the given style on fmt, calls f(), then restores the previous style. It is useful in imperative-style printers (a sequence of "print a; print b; …").
Available only on OCaml >= 4.08.
val to_string : 'a printer -> 'a -> stringval of_chan : Stdlib.out_channel -> tAlias to Format.formatter_of_out_channel.
val with_out_chan : Stdlib.out_channel -> ( t -> 'a ) -> 'awith_out_chan oc f turns oc into a formatter fmt, and call f fmt. Behaves like f fmt from then on, but whether the call to f fails or returns, fmt is flushed before the call terminates.
val stdout : tval stderr : tval sprintf : ( 'a, t, unit, string ) Stdlib.format4 -> 'aPrint into a string any format string that would usually be compatible with fprintf. Like Format.asprintf.
val sprintf_no_color : ( 'a, t, unit, string ) Stdlib.format4 -> 'aLike sprintf but never prints colors.
val sprintf_dyn_color :
+ colors:bool ->
+ ( 'a, t, unit, string ) Stdlib.format4 ->
+ 'aLike sprintf but enable/disable colors depending on colors.
Example:
(* with colors *)
+CCFormat.sprintf_dyn_color ~colors:true "@{<Red>%a@}"
+ CCFormat.Dump.(list int) [1;2;3] |> print_endline;;
+
+(* without colors *)
+CCFormat.sprintf_dyn_color ~colors:false "@{<Red>%a@}"
+ CCFormat.Dump.(list int) [1;2;3] |> print_endline;;Like fprintf but enable/disable colors depending on colors.
val ksprintf :
+ ?margin:int ->
+ f:( string -> 'b ) ->
+ ( 'a, Stdlib.Format.formatter, unit, 'b ) Stdlib.format4 ->
+ 'aksprintf fmt ~f formats using fmt, in a way similar to sprintf, and then calls f on the resulting string.
val to_file : string -> ( 'a, t, unit, unit ) Stdlib.format4 -> 'aPrint to the given file.
Print structures as OCaml values, so that they can be parsed back by OCaml (typically, in the toplevel, for debugging).
Example:
Format.printf "%a@." CCFormat.Dump.(list int) CCList.(1 -- 200);;
+
+Format.printf "%a@." CCFormat.Dump.(array (list (pair int bool)))
+ [| [1, true; 2, false]; []; [42, false] |];;module Dump : sig ... endmodule Infix : sig ... endCCFun.Infix(f %> g) x or (%>) f g x is g (f x). Alias to compose.
Monad.1-XCCFun.Monadmodule X : sig ... endtype 'a t = X.t -> 'aval return : 'a -> 'a tMonadic return.
CCFunBasic operations on Functions
compose_binop f g is fun x y -> g (f x) (f y). Example (partial order): List.sort (compose_binop fst CCInt.compare) [1, true; 2, false; 1, false].
curry f x y is f (x,y). Convert a function which accepts a pair of arguments into a function which accepts two arguments.
uncurry f (x,y) is f x y. Convert a function which accepts a two arguments into a function which accepts a pair of arguments.
tap f x evaluates f x, discards it, then returns x. Useful in a pipeline, for instance:
CCArray.(1 -- 10)
+|> tap CCArray.shuffle
+|> tap @@ CCArray.sort Stdlib.compareLexicographic combination of comparison functions.
finally ~h f calls f () and returns its result. If it raises, the same exception is raised; in any case, h () is called after f () terminates. If h () raises an exception, then this exception will be passed on and any exception that may have been raised by f () is lost.
finally1 ~h f x is the same as f x, but after the computation, h () is called whether f x rose an exception or not. If h () raises an exception, then this exception will be passed on and any exception that may have been raised by f () is lost.
finally2 ~h f x y is the same as f x y, but after the computation, h () is called whether f x y rose an exception or not. If h () raises an exception, then this exception will be passed on and any exception that may have been raised by f () is lost.
opaque_identity x is like x, but prevents Flambda from using x's definition for optimizing it. (flambda is an optimization/inlining pass in OCaml >= 4.03).
iterate n f is f iterated n times. That is to say, iterate 0 f x is x, iterate 1 f x is f x, iterate 2 f x is f (f x), etc.
Infix operators.
module Infix : sig ... endinclude module type of Infix(f %> g) x or (%>) f g x is g (f x). Alias to compose.
Functions with a fixed domain are monads in their codomain.
CCHashHash combinators
The API of this module is stable as per semantic versioning, like the rest of containers. However the exact implementation of hashing function can change and should not be relied on (i.e. hashing a value always returns the same integer within a run of a program, not across versions of OCaml and Containers).
type 'a t = 'a -> hashA hash function for values of type 'a.
val const0 : _ tAlways return 0. Useful for ignoring elements. Example: Hash.(pair string const0) will map pairs ("a", 1) and ("a", 2) to the same hash, but not the same as ("b", 1).
val int : int tval bool : bool tval char : char tval int32 : int32 tval int64 : int64 tval nativeint : nativeint tval slice : string -> int -> int tslice s i len state hashes the slice i, …, i+len-1 of s into state.
val bytes : bytes tHash a byte array.
val string : string tmap f h is the hasher that takes x, and uses h to hash f x.
For example:
module Str_set = Set.Make(String)
+
+let hash_str_set : Str_set.t CCHash.t = CCHash.(map Str_set.to_seq @@ seq string)val poly : 'a tpoly x is Hashtbl.hash x. The regular polymorphic hash function.
Commutative version of list. Lists that are equal up to permutation will have the same hash.
Commutative version of array. Arrays that are equal up to permutation will have the same hash.
CCHashtbl.Makeget tbl k finds a binding for the key k if present, or returns None if no value is found. Safe version of Hashtbl.find.
get_or tbl k ~default returns the value associated to k if present, and returns default otherwise (if k doesn't belong in tbl).
add_list tbl x y adds y to the list x is bound to. If x is not bound, it becomes bound to y.
incr ?by tbl x increments or initializes the counter associated with x. If get tbl x = None, then after update, get tbl x = Some 1; otherwise, if get tbl x = Some n, now get tbl x = Some (n+1).
decr ?by tbl x is like incr but subtract 1 (or the value of by). If the value reaches 0, the key is removed from the table. This does nothing if the key is not already present in the table.
keys_list tbl is the list of keys in tbl. If the key is in the Hashtable multiple times, all occurrences will be returned.
val values_list : 'a t -> 'a listvalues_list t is the list of values in t.
Map on a hashtable's items, collect into a list.
Add the corresponding pairs to the table, using Hashtbl.add.
Add the corresponding pairs to the table, using Hashtbl.add. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
Add the corresponding pairs to the table, using Hashtbl.add. Renamed from add_std_seq since 3.0.
Add the corresponding pairs to the table, using Hashtbl.add. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
From the given bindings, added in order. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
From the given bindings, added in order. Renamed from of_std_seq since 3.0.
From the given bindings, added in order. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
add_iter_count tbl i increments the count of each element of i by calling incr. This is useful for counting how many times each element of i occurs.
add_seq_count tbl seq increments the count of each element of seq by calling incr. This is useful for counting how many times each element of seq occurs. Renamed from of_std_seq_count since 3.0.
Like add_seq_count, but allocates a new table and returns it.
Like add_seq_count, but allocates a new table and returns it. Renamed from of_std_seq_count since 3.0.
to_list tbl returns the list of (key,value) bindings (order unspecified).
of_list l builds a table from the given list l of bindings k_i -> v_i, added in order using add. If a key occurs several times, it will be added several times, and the visible binding will be the last one.
of_list l builds a table from the given list l of bindings k_i -> v_i. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
update tbl ~f ~k updates key k by calling f k (Some v) if k was mapped to v, or f k None otherwise; if the call returns None then k is removed/stays removed, if the call returns Some v' then the binding k -> v' is inserted using Hashtbl.replace.
get_or_add tbl ~k ~f finds and returns the binding of k in tbl, if it exists. If it does not exist, then f k is called to obtain a new binding v; k -> v is added to tbl and v is returned.
val pp :
+ ?pp_start:unit printer ->
+ ?pp_stop:unit printer ->
+ ?pp_sep:unit printer ->
+ ?pp_arrow:unit printer ->
+ key printer ->
+ 'a printer ->
+ 'a t printerpp ~pp_start ~pp_stop ~pp_sep ~pp arrow pp_k pp_v returns a table printer given a pp_k printer for individual key and a pp_v printer for individual value. pp_start and pp_stop control the opening and closing delimiters, by default print nothing. pp_sep control the separator between binding. pp_arrow control the arrow between the key and value. Renamed from print since 2.0.
CCHashtbl.Polyget tbl k finds a binding for the key k if present, or returns None if no value is found. Safe version of Hashtbl.find.
get_or tbl k ~default returns the value associated to k if present, and returns default otherwise (if k doesn't belong in tbl).
val keys : ( 'a, 'b ) Stdlib.Hashtbl.t -> 'a iterkeys tbl f iterates on keys (similar order as Hashtbl.iter).
val values : ( 'a, 'b ) Stdlib.Hashtbl.t -> 'b itervalues tbl f iterates on values in the table tbl.
keys_list tbl is the list of keys in tbl. If the key is in the Hashtable multiple times, all occurrences will be returned.
values_list tbl is the list of values in tbl.
map_list f tbl maps on a tbl's items. Collect into a list.
incr ?by tbl x increments or initializes the counter associated with x. If get tbl x = None, then after update, get tbl x = Some 1; otherwise, if get tbl x = Some n, now get tbl x = Some (n+1).
decr ?by tbl x is like incr but subtract 1 (or the value of by). If the value reaches 0, the key is removed from the table. This does nothing if the key is not already present in the table.
val to_iter : ( 'a, 'b ) Stdlib.Hashtbl.t -> ('a * 'b) iterIterate on bindings in the table.
add_list tbl x y adds y to the list x is bound to. If x is not bound, it becomes bound to y.
val add_iter : ( 'a, 'b ) Stdlib.Hashtbl.t -> ('a * 'b) iter -> unitAdd the corresponding pairs to the table, using Hashtbl.add.
val add_iter_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ( 'a, 'b ) Stdlib.Hashtbl.t ->
+ ('a * 'b) iter ->
+ unitAdd the corresponding pairs to the table, using Hashtbl.add. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
Add the corresponding pairs to the table, using Hashtbl.add. Renamed from add_std_seq since 3.0.
val add_seq_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ( 'a, 'b ) Stdlib.Hashtbl.t ->
+ ('a * 'b) Stdlib.Seq.t ->
+ unitAdd the corresponding pairs to the table. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
val of_iter : ('a * 'b) iter -> ( 'a, 'b ) Stdlib.Hashtbl.tFrom the given bindings, added in order.
val of_iter_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ('a * 'b) iter ->
+ ( 'a, 'b ) Stdlib.Hashtbl.tFrom the given bindings, added in order. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
From the given bindings, added in order. Renamed from of_std_seq since 3.0.
val of_seq_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ('a * 'b) Stdlib.Seq.t ->
+ ( 'a, 'b ) Stdlib.Hashtbl.tFrom the given bindings, added in order. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
val add_iter_count : ( 'a, int ) Stdlib.Hashtbl.t -> 'a iter -> unitadd_iter_count tbl i increments the count of each element of i by calling incr. This is useful for counting how many times each element of i occurs.
add_seq_count tbl seq increments the count of each element of seq by calling incr. This is useful for counting how many times each element of seq occurs. Renamed from add_std_seq_count since 3.0.
val of_iter_count : 'a iter -> ( 'a, int ) Stdlib.Hashtbl.tLike add_seq_count, but allocates a new table and returns it.
Like add_seq_count, but allocates a new table and returns it. Renamed from of_std_seq_count since 3.0.
to_list tbl returns the list of (key,value) bindings (order unspecified).
of_list l builds a table from the given list l of bindings k_i -> v_i, added in order using add. If a key occurs several times, it will be added several times, and the visible binding will be the last one.
val of_list_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ('a * 'b) list ->
+ ( 'a, 'b ) Stdlib.Hashtbl.tFrom the given bindings, added in order. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
val update :
+ ( 'a, 'b ) Stdlib.Hashtbl.t ->
+ f:( 'a -> 'b option -> 'b option ) ->
+ k:'a ->
+ unitupdate tbl ~f ~k updates key k by calling f k (Some v) if k was mapped to v, or f k None otherwise; if the call returns None then k is removed/stays removed, if the call returns Some v' then the binding k -> v' is inserted using Hashtbl.replace.
get_or_add tbl ~k ~f finds and returns the binding of k in tbl, if it exists. If it does not exist, then f k is called to obtain a new binding v; k -> v is added to tbl and v is returned.
val pp :
+ ?pp_start:unit printer ->
+ ?pp_stop:unit printer ->
+ ?pp_sep:unit printer ->
+ ?pp_arrow:unit printer ->
+ 'a printer ->
+ 'b printer ->
+ ( 'a, 'b ) Stdlib.Hashtbl.t printerpp ~pp_start ~pp_stop ~pp_sep ~pp arrow pp_k pp_v returns a table printer given a pp_k printer for individual key and a pp_v printer for individual value. pp_start and pp_stop control the opening and closing delimiters, by default print nothing. pp_sep control the separator between binding. pp_arrow control the arrow between the key and value. Renamed from print since 2.0.
CCHashtblExtension to the standard Hashtbl
This sub-module contains the extension of the standard polymorphic Hashtbl.
module Poly : sig ... endinclude module type of Polyget tbl k finds a binding for the key k if present, or returns None if no value is found. Safe version of Hashtbl.find.
get_or tbl k ~default returns the value associated to k if present, and returns default otherwise (if k doesn't belong in tbl).
val keys : ( 'a, 'b ) Stdlib.Hashtbl.t -> 'a iterkeys tbl f iterates on keys (similar order as Hashtbl.iter).
val values : ( 'a, 'b ) Stdlib.Hashtbl.t -> 'b itervalues tbl f iterates on values in the table tbl.
keys_list tbl is the list of keys in tbl. If the key is in the Hashtable multiple times, all occurrences will be returned.
values_list tbl is the list of values in tbl.
map_list f tbl maps on a tbl's items. Collect into a list.
incr ?by tbl x increments or initializes the counter associated with x. If get tbl x = None, then after update, get tbl x = Some 1; otherwise, if get tbl x = Some n, now get tbl x = Some (n+1).
decr ?by tbl x is like incr but subtract 1 (or the value of by). If the value reaches 0, the key is removed from the table. This does nothing if the key is not already present in the table.
val to_iter : ( 'a, 'b ) Stdlib.Hashtbl.t -> ('a * 'b) iterIterate on bindings in the table.
add_list tbl x y adds y to the list x is bound to. If x is not bound, it becomes bound to y.
val add_iter : ( 'a, 'b ) Stdlib.Hashtbl.t -> ('a * 'b) iter -> unitAdd the corresponding pairs to the table, using Hashtbl.add.
val add_iter_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ( 'a, 'b ) Stdlib.Hashtbl.t ->
+ ('a * 'b) iter ->
+ unitAdd the corresponding pairs to the table, using Hashtbl.add. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
Add the corresponding pairs to the table, using Hashtbl.add. Renamed from add_std_seq since 3.0.
val add_seq_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ( 'a, 'b ) Stdlib.Hashtbl.t ->
+ ('a * 'b) Stdlib.Seq.t ->
+ unitAdd the corresponding pairs to the table. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
val of_iter : ('a * 'b) iter -> ( 'a, 'b ) Stdlib.Hashtbl.tFrom the given bindings, added in order.
val of_iter_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ('a * 'b) iter ->
+ ( 'a, 'b ) Stdlib.Hashtbl.tFrom the given bindings, added in order. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
From the given bindings, added in order. Renamed from of_std_seq since 3.0.
val of_seq_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ('a * 'b) Stdlib.Seq.t ->
+ ( 'a, 'b ) Stdlib.Hashtbl.tFrom the given bindings, added in order. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
val add_iter_count : ( 'a, int ) Stdlib.Hashtbl.t -> 'a iter -> unitadd_iter_count tbl i increments the count of each element of i by calling incr. This is useful for counting how many times each element of i occurs.
add_seq_count tbl seq increments the count of each element of seq by calling incr. This is useful for counting how many times each element of seq occurs. Renamed from add_std_seq_count since 3.0.
val of_iter_count : 'a iter -> ( 'a, int ) Stdlib.Hashtbl.tLike add_seq_count, but allocates a new table and returns it.
Like add_seq_count, but allocates a new table and returns it. Renamed from of_std_seq_count since 3.0.
to_list tbl returns the list of (key,value) bindings (order unspecified).
of_list l builds a table from the given list l of bindings k_i -> v_i, added in order using add. If a key occurs several times, it will be added several times, and the visible binding will be the last one.
val of_list_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ('a * 'b) list ->
+ ( 'a, 'b ) Stdlib.Hashtbl.tFrom the given bindings, added in order. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
val update :
+ ( 'a, 'b ) Stdlib.Hashtbl.t ->
+ f:( 'a -> 'b option -> 'b option ) ->
+ k:'a ->
+ unitupdate tbl ~f ~k updates key k by calling f k (Some v) if k was mapped to v, or f k None otherwise; if the call returns None then k is removed/stays removed, if the call returns Some v' then the binding k -> v' is inserted using Hashtbl.replace.
get_or_add tbl ~k ~f finds and returns the binding of k in tbl, if it exists. If it does not exist, then f k is called to obtain a new binding v; k -> v is added to tbl and v is returned.
val pp :
+ ?pp_start:unit printer ->
+ ?pp_stop:unit printer ->
+ ?pp_sep:unit printer ->
+ ?pp_arrow:unit printer ->
+ 'a printer ->
+ 'b printer ->
+ ( 'a, 'b ) Stdlib.Hashtbl.t printerpp ~pp_start ~pp_stop ~pp_sep ~pp arrow pp_k pp_v returns a table printer given a pp_k printer for individual key and a pp_v printer for individual value. pp_start and pp_stop control the opening and closing delimiters, by default print nothing. pp_sep control the separator between binding. pp_arrow control the arrow between the key and value. Renamed from print since 2.0.
module type S = sig ... endCCHashtbl.Sget tbl k finds a binding for the key k if present, or returns None if no value is found. Safe version of Hashtbl.find.
get_or tbl k ~default returns the value associated to k if present, and returns default otherwise (if k doesn't belong in tbl).
add_list tbl x y adds y to the list x is bound to. If x is not bound, it becomes bound to y.
incr ?by tbl x increments or initializes the counter associated with x. If get tbl x = None, then after update, get tbl x = Some 1; otherwise, if get tbl x = Some n, now get tbl x = Some (n+1).
decr ?by tbl x is like incr but subtract 1 (or the value of by). If the value reaches 0, the key is removed from the table. This does nothing if the key is not already present in the table.
keys_list tbl is the list of keys in tbl. If the key is in the Hashtable multiple times, all occurrences will be returned.
val values_list : 'a t -> 'a listvalues_list t is the list of values in t.
Map on a hashtable's items, collect into a list.
Add the corresponding pairs to the table, using Hashtbl.add.
Add the corresponding pairs to the table, using Hashtbl.add. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
Add the corresponding pairs to the table, using Hashtbl.add. Renamed from add_std_seq since 3.0.
Add the corresponding pairs to the table, using Hashtbl.add. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
From the given bindings, added in order. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
From the given bindings, added in order. Renamed from of_std_seq since 3.0.
From the given bindings, added in order. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
add_iter_count tbl i increments the count of each element of i by calling incr. This is useful for counting how many times each element of i occurs.
add_seq_count tbl seq increments the count of each element of seq by calling incr. This is useful for counting how many times each element of seq occurs. Renamed from of_std_seq_count since 3.0.
Like add_seq_count, but allocates a new table and returns it.
Like add_seq_count, but allocates a new table and returns it. Renamed from of_std_seq_count since 3.0.
to_list tbl returns the list of (key,value) bindings (order unspecified).
of_list l builds a table from the given list l of bindings k_i -> v_i, added in order using add. If a key occurs several times, it will be added several times, and the visible binding will be the last one.
of_list l builds a table from the given list l of bindings k_i -> v_i. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
update tbl ~f ~k updates key k by calling f k (Some v) if k was mapped to v, or f k None otherwise; if the call returns None then k is removed/stays removed, if the call returns Some v' then the binding k -> v' is inserted using Hashtbl.replace.
get_or_add tbl ~k ~f finds and returns the binding of k in tbl, if it exists. If it does not exist, then f k is called to obtain a new binding v; k -> v is added to tbl and v is returned.
val pp :
+ ?pp_start:unit printer ->
+ ?pp_stop:unit printer ->
+ ?pp_sep:unit printer ->
+ ?pp_arrow:unit printer ->
+ key printer ->
+ 'a printer ->
+ 'a t printerpp ~pp_start ~pp_stop ~pp_sep ~pp arrow pp_k pp_v returns a table printer given a pp_k printer for individual key and a pp_v printer for individual value. pp_start and pp_stop control the opening and closing delimiters, by default print nothing. pp_sep control the separator between binding. pp_arrow control the arrow between the key and value. Renamed from print since 2.0.
Make.1-ECCHeap.Makemodule E : PARTIAL_ORDtype elt = E.tval empty : tempty returns the empty heap.
val is_empty : t -> boolis_empty h returns true if the heap h is empty.
filter p h filters values, only retaining the ones that satisfy the predicate p. Linear time at least.
take h extracts and returns the minimum element, and the new heap (without this element), or None if the heap h is empty.
delete_one eq x h uses eq to find one occurrence of a value x if it exist in the heap h, and delete it. If h do not contain x then it return h.
delete_all eq x h uses eq to find all x in h and delete them. If h do not contain x then it return h. The difference with filter is that delete_all stops as soon as it enters a subtree whose root is bigger than the element.
iter f h iterates over the heap h invoking f with the current element.
val size : t -> intsize h is the number of elements in the heap h. Linear complexity.
to_list_sorted h returns the elements of the heap h in increasing order.
add_list h l adds the elements of the list l into the heap h. An element occurring several times will be added that many times to the heap.
add_seq h seq is like add_list. Renamed from add_std_seq since 3.0.
of_seq seq builds a heap from a given Seq.t. Complexity: O(n log n). Renamed from of_seq since 3.0.
to_seq h returns a Seq.t of the elements of the heap h. Renamed from to_std_seq since 3.0.
to_iter_sorted h returns a iter by iterating on the elements of h, in increasing order.
to_seq_sorted h returns a Seq.t by iterating on the elements of h, in increasing order. Renamed from to_std_seq_sorted since 3.0.
to_string ?sep f h prints the heap h in a string using sep as a given separator (default ",") between each element (converted to a string using f).
val pp :
+ ?pp_start:unit printer ->
+ ?pp_stop:unit printer ->
+ ?pp_sep:unit printer ->
+ elt printer ->
+ t printerpp ?pp_start ?pp_stop ?pp_sep ppf h prints h on ppf. Each element is formatted with ppf, pp_start is called at the beginning, pp_stop is called at the end, pp_sep is called between each elements. By defaults pp_start and pp_stop does nothing and pp_sep defaults to (fun out -> Format.fprintf out ",@ "). Renamed from print since 2.0
Make_from_compare.1-ECCHeap.Make_from_compareA convenient version of Make that take a TOTAL_ORD instead of a partially ordered module. It allow to directly pass modules that implement compare without implementing leq explicitly
type elt = E.tval empty : tempty returns the empty heap.
val is_empty : t -> boolis_empty h returns true if the heap h is empty.
filter p h filters values, only retaining the ones that satisfy the predicate p. Linear time at least.
take h extracts and returns the minimum element, and the new heap (without this element), or None if the heap h is empty.
delete_one eq x h uses eq to find one occurrence of a value x if it exist in the heap h, and delete it. If h do not contain x then it return h.
delete_all eq x h uses eq to find all x in h and delete them. If h do not contain x then it return h. The difference with filter is that delete_all stops as soon as it enters a subtree whose root is bigger than the element.
iter f h iterates over the heap h invoking f with the current element.
val size : t -> intsize h is the number of elements in the heap h. Linear complexity.
to_list_sorted h returns the elements of the heap h in increasing order.
add_list h l adds the elements of the list l into the heap h. An element occurring several times will be added that many times to the heap.
add_seq h seq is like add_list. Renamed from add_std_seq since 3.0.
of_seq seq builds a heap from a given Seq.t. Complexity: O(n log n). Renamed from of_seq since 3.0.
to_seq h returns a Seq.t of the elements of the heap h. Renamed from to_std_seq since 3.0.
to_iter_sorted h returns a iter by iterating on the elements of h, in increasing order.
to_seq_sorted h returns a Seq.t by iterating on the elements of h, in increasing order. Renamed from to_std_seq_sorted since 3.0.
to_string ?sep f h prints the heap h in a string using sep as a given separator (default ",") between each element (converted to a string using f).
val pp :
+ ?pp_start:unit printer ->
+ ?pp_stop:unit printer ->
+ ?pp_sep:unit printer ->
+ elt printer ->
+ t printerpp ?pp_start ?pp_stop ?pp_sep ppf h prints h on ppf. Each element is formatted with ppf, pp_start is called at the beginning, pp_stop is called at the end, pp_sep is called between each elements. By defaults pp_start and pp_stop does nothing and pp_sep defaults to (fun out -> Format.fprintf out ",@ "). Renamed from print since 2.0
CCHeapLeftist Heaps
Implementation following Okasaki's book.
type 'a ktree = unit -> [ `Nil | `Node of 'a * 'a ktree list ]module type PARTIAL_ORD = sig ... endmodule type TOTAL_ORD = sig ... endmodule type S = sig ... endCCHeap.PARTIAL_ORDCCHeap.Sval empty : tempty returns the empty heap.
val is_empty : t -> boolis_empty h returns true if the heap h is empty.
filter p h filters values, only retaining the ones that satisfy the predicate p. Linear time at least.
take h extracts and returns the minimum element, and the new heap (without this element), or None if the heap h is empty.
delete_one eq x h uses eq to find one occurrence of a value x if it exist in the heap h, and delete it. If h do not contain x then it return h.
delete_all eq x h uses eq to find all x in h and delete them. If h do not contain x then it return h. The difference with filter is that delete_all stops as soon as it enters a subtree whose root is bigger than the element.
iter f h iterates over the heap h invoking f with the current element.
val size : t -> intsize h is the number of elements in the heap h. Linear complexity.
to_list_sorted h returns the elements of the heap h in increasing order.
add_list h l adds the elements of the list l into the heap h. An element occurring several times will be added that many times to the heap.
add_seq h seq is like add_list. Renamed from add_std_seq since 3.0.
of_seq seq builds a heap from a given Seq.t. Complexity: O(n log n). Renamed from of_seq since 3.0.
to_seq h returns a Seq.t of the elements of the heap h. Renamed from to_std_seq since 3.0.
to_iter_sorted h returns a iter by iterating on the elements of h, in increasing order.
to_seq_sorted h returns a Seq.t by iterating on the elements of h, in increasing order. Renamed from to_std_seq_sorted since 3.0.
to_string ?sep f h prints the heap h in a string using sep as a given separator (default ",") between each element (converted to a string using f).
val pp :
+ ?pp_start:unit printer ->
+ ?pp_stop:unit printer ->
+ ?pp_sep:unit printer ->
+ elt printer ->
+ t printerpp ?pp_start ?pp_stop ?pp_sep ppf h prints h on ppf. Each element is formatted with ppf, pp_start is called at the beginning, pp_stop is called at the end, pp_sep is called between each elements. By defaults pp_start and pp_stop does nothing and pp_sep defaults to (fun out -> Format.fprintf out ",@ "). Renamed from print since 2.0
CCHeap.TOTAL_ORDCCIO.FileA file should be represented by its absolute path, but currently this is not enforced.
val to_string : t -> stringval make : string -> tBuild a file representation from a path (absolute or relative).
val exists : t -> boolval is_directory : t -> boolval remove_exn : t -> unitremove_exn path tries to remove the file at path from the file system.
val remove_noerr : t -> unitLike remove_exn but do not raise any exception on failure.
read_dir d returns a sequence of files and directory contained in the directory d (or an empty stream if d is not a directory).
val read_exn : t -> stringRead the content of the given file, or raises some exception.
val append_exn : t -> string -> unitAppend the given string into the given file, possibly raising.
val write_exn : t -> string -> unitWrite the given string into the given file, possibly raising.
type walk_item = [ `File | `Dir ] * tLike read_dir (with recurse=true), this function walks a directory recursively and yields either files or directories. Is a file anything that doesn't satisfy is_directory (including symlinks, etc.)
Like walk but returns a list (therefore it's eager and might take some time on large directories).
val show_walk_item : walk_item -> stringval with_temp :
+ ?temp_dir:string ->
+ prefix:string ->
+ suffix:string ->
+ ( string -> 'a ) ->
+ 'awith_temp ~prefix ~suffix f will call f with the name of a new temporary file (located in temp_dir). After f returns, the file is deleted. Best to be used in combination with with_out. See Filename.temp_file.
CCIOIO Utils
Simple utilities to deal with basic Input/Output tasks in a resource-safe way. For advanced IO tasks, the user is advised to use something like Lwt or Async, that are far more comprehensive.
Examples:
# let l = CCIO.(with_in "/tmp/some_file" read_lines_l);;# CCIO.(
+ with_in "/tmp/input"
+ (fun ic ->
+ let chunks = read_chunks_gen ic in
+ with_out ~flags:[Open_binary; Open_creat] ~mode:0o644 "/tmp/output"
+ (fun oc ->
+ write_gen oc chunks
+ )
+ )
+ ) ;;chunks must be used in the scope of ic. This will raise an error:# CCIO.(
+ let chunks =
+ with_in "/tmp/input"
+ (fun ic -> read_chunks_gen ic)
+ in
+ with_out ~flags:[Open_binary;Open_creat] ~mode:0o644 "/tmp/output"
+ (fun oc ->
+ write_gen oc chunks
+ )
+ ) ;;See Gen in the gen library.
val with_in :
+ ?mode:int ->
+ ?flags:Stdlib.open_flag list ->
+ string ->
+ ( Stdlib.in_channel -> 'a ) ->
+ 'aOpen an input file with the given optional flag list, calls the function on the input channel. When the function raises or returns, the channel is closed.
val read_chunks_gen : ?size:int -> Stdlib.in_channel -> string genRead the channel's content into chunks of size at most size. NOTE the generator must be used within the lifetime of the channel, see warning at the top of the file.
Read the channel's content into chunks of size at most size. NOTE the generator must be used within the lifetime of the channel, see warning at the top of the file.
val read_chunks_iter : ?size:int -> Stdlib.in_channel -> string iterRead the channel's content into chunks of size at most size
Read a line from the channel. Returns None if the input is terminated. The "\n" is removed from the line.
val read_lines_gen : Stdlib.in_channel -> string genRead all lines. The generator should be traversed only once. NOTE the generator must be used within the lifetime of the channel, see warning at the top of the file.
Read all lines. NOTE the seq must be used within the lifetime of the channel, see warning at the top of the file.
val read_lines_iter : Stdlib.in_channel -> string iterRead all lines.
Read the whole channel into a buffer, then converted into a string.
Read the whole channel into a mutable byte array.
val with_out :
+ ?mode:int ->
+ ?flags:Stdlib.open_flag list ->
+ string ->
+ ( Stdlib.out_channel -> 'a ) ->
+ 'aLike with_in but for an output channel.
val with_out_a :
+ ?mode:int ->
+ ?flags:Stdlib.open_flag list ->
+ string ->
+ ( Stdlib.out_channel -> 'a ) ->
+ 'aLike with_out but with the [Open_append; Open_creat; Open_wronly] flags activated, to append to the file.
Write the given string on the channel, followed by "\n".
val write_gen : ?sep:string -> Stdlib.out_channel -> string gen -> unitWrite the given strings on the output. If provided, add sep between every two strings (but not at the end).
Write the given strings on the output. If provided, add sep between every two strings (but not at the end).
val write_lines : Stdlib.out_channel -> string gen -> unitWrite every string on the output, followed by "\n".
val write_lines_iter : Stdlib.out_channel -> string iter -> unitWrite every string on the output, followed by "\n".
Write every string on the output, followed by "\n".
copy_into ic oc writes the content of ic into oc. It is a blocking call.
tee funs gen behaves like gen, but each element is given to every function f in funs at the time the element is produced. The returned generator will raise any exception that f raises
How to list recursively files in a directory:
# let files = CCIO.File.read_dir ~recurse:true (CCIO.File.make "/tmp");;
+# CCIO.write_lines stdout files;;See File.walk if you also need to list directories:
# let content = CCIO.File.walk (CCIO.File.make "/tmp");;
+# Gen.map CCIO.File.show_walk_item content |> CCIO.write_lines stdout;;module File : sig ... endCCInt.InfixCCIntBasic Int functions
val zero : tzero is the integer 0.
val one : tone is the integer 1.
val minus_one : tminus_one is the integer -1.
val max_int : tmax_int is the maximum integer.
val min_int : tmin_int is the minimum integer.
compare x y is the comparison function for integers with the same specification as Stdlib.compare.
val hash : t -> inthash x computes the hash of x.
val sign : t -> intsign x return 0 if x = 0, -1 if x < 0 and 1 if x > 0. Same as compare x 0.
pow base exponent returns base raised to the power of exponent. pow x y = x^y for positive integers x and y. Raises Invalid_argument if x = y = 0 or y < 0.
floor_div x n is integer division rounding towards negative infinity. It satisfies x = m * floor_div x n + rem x n.
val random : int -> t random_genval random_small : t random_genval random_range : int -> int -> t random_genval to_float : t -> floatto_float is the same as float_of_int
val to_string : t -> stringto_string x returns the string representation of the integer x, in signed decimal.
val of_string : string -> t optionof_string s converts the given string s into an integer. Safe version of of_string_exn.
val of_string_exn : string -> tof_string_exn s converts the given string s to an integer. Alias to int_of_string.
val of_float : float -> tof_float x converts the given floating-point number x to an integer. Alias to int_of_float.
val to_string_binary : t -> stringto_string_binary x returns the string representation of the integer x, in binary.
range_by ~step i j iterates on integers from i to j included, where the difference between successive elements is step. Use a negative step for a decreasing list.
range i j iterates on integers from i to j included . It works both for decreasing and increasing ranges.
range' i j is like range but the second bound j is excluded. For instance range' 0 5 = Iter.of_list [0;1;2;3;4].
val popcount : t -> intNumber of bits set to 1
module Infix : sig ... endinclude module type of InfixCCInt32.Infixx / y is the integer quotient of x and y. Integer division. Raise Division_by_zero if the second argument y is zero. This division rounds the real quotient of its arguments towards zero, as specified for Stdlib.(/).
x mod y is the integer remainder of x / y. If y <> zero, the result of x mod y satisfies the following properties: zero <= x mod y < abs y and x = ((x / y) * y) + (x mod y). If y = 0, x mod y raises Division_by_zero.
x lsl y shifts x to the left by y bits, filling in with zeroes. The result is unspecified if y < 0 or y >= 32.
x lsr y shifts x to the right by y bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of x. The result is unspecified if y < 0 or y >= 32.
x asr y shifts x to the right by y bits. This is an arithmetic shift: the sign bit of x is replicated and inserted in the vacated bits. The result is unspecified if y < 0 or y >= 32.
CCInt32Helpers for 32-bit integers.
This module provides operations on the type int32 of signed 32-bit integers. Unlike the built-in int type, the type int32 is guaranteed to be exactly 32-bit wide on all platforms. All arithmetic operations over int32 are taken modulo 232.
Performance notice: values of type int32 occupy more memory space than values of type int, and arithmetic operations on int32 are generally slower than those on int. Use int32 only when the application requires exact 32-bit arithmetic.
include module type of struct include Stdlib.Int32 endval hash : t -> inthash x computes the hash of x. Like Stdlib.abs(to_intx).
val sign : t -> intsign x return 0 if x = 0, -1 if x < 0 and 1 if x > 0. Same as compare x zero.
pow base exponent returns base raised to the power of exponent. pow x y = x^y for positive integers x and y. Raises Invalid_argument if x = y = 0 or y < 0.
val popcount : t -> intNumber of bits set to 1.
floor_div x n is integer division rounding towards negative infinity. It satisfies x = m * floor_div x n + rem x n.
range_by ~step i j iterates on integers from i to j included, where the difference between successive elements is step. Use a negative step for a decreasing list.
range i j iterates on integers from i to j included . It works both for decreasing and increasing ranges.
range' i j is like range but the second bound j is excluded. For instance range' 0 5 = Iter.of_list [0;1;2;3;4].
val random : t -> t random_genval random_small : t random_genval random_range : t -> t -> t random_genval of_string : string -> t optionof_string s is the safe version of of_string_exn. Like of_string_exn, but return None instead of raising.
val of_string_exn : string -> tof_string_exn s converts the given string s into a 32-bit integer. Alias to Int32.of_string. The string is read in decimal (by default, or if the string begins with 0u) or in hexadecimal, octal or binary if the string begins with 0x, 0o or 0b respectively.
The 0u prefix reads the input as an unsigned integer in the range [0, 2*CCInt32.max_int+1]. If the input exceeds CCInt32.max_int it is converted to the signed integer CCInt32.min_int + input - CCInt32.max_int - 1.
The _ (underscore) character can appear anywhere in the string and is ignored. Raise Failure "Int32.of_string" if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type int32.
val to_string_binary : t -> stringto_string_binary x returns the string representation of the integer x, in binary.
module Infix : sig ... endinclude module type of Infixx / y is the integer quotient of x and y. Integer division. Raise Division_by_zero if the second argument y is zero. This division rounds the real quotient of its arguments towards zero, as specified for Stdlib.(/).
x mod y is the integer remainder of x / y. If y <> zero, the result of x mod y satisfies the following properties: zero <= x mod y < abs y and x = ((x / y) * y) + (x mod y). If y = 0, x mod y raises Division_by_zero.
x lsl y shifts x to the left by y bits, filling in with zeroes. The result is unspecified if y < 0 or y >= 32.
x lsr y shifts x to the right by y bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of x. The result is unspecified if y < 0 or y >= 32.
x asr y shifts x to the right by y bits. This is an arithmetic shift: the sign bit of x is replicated and inserted in the vacated bits. The result is unspecified if y < 0 or y >= 32.
CCInt64.Infixx / y is the integer quotient of x and y. Integer division. Raise Division_by_zero if the second argument y is zero. This division rounds the real quotient of its arguments towards zero, as specified for Stdlib.(/).
x mod y is the integer remainder of x / y. If y <> zero, the result of x mod y satisfies the following properties: zero <= x mod y < abs y and x = ((x / y) * y) + (x mod y). If y = 0, x mod y raises Division_by_zero.
x lsl y shifts x to the left by y bits, filling in with zeroes. The result is unspecified if y < 0 or y >= 64.
x lsr y shifts x to the right by y bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of x. The result is unspecified if y < 0 or y >= 64.
x asr y shifts x to the right by y bits. This is an arithmetic shift: the sign bit of x is replicated and inserted in the vacated bits. The result is unspecified if y < 0 or y >= 64.
CCInt64Helpers for 64-bit integers.
This module provides operations on the type int64 of signed 64-bit integers. Unlike the built-in int type, the type int64 is guaranteed to be exactly 64-bit wide on all platforms. All arithmetic operations over int64 are taken modulo 264.
Performance notice: values of type int64 occupy more memory space than values of type int, and arithmetic operations on int64 are generally slower than those on int. Use int64 only when the application requires exact 64-bit arithmetic.
include module type of struct include Stdlib.Int64 endval hash : t -> inthash x computes the hash of x, a non-negative integer. Uses FNV since NEXT_RELEASE
val popcount : t -> intNumber of bits set to 1.
val sign : t -> intsign x return 0 if x = 0, -1 if x < 0 and 1 if x > 0. Same as compare x zero.
pow base exponent returns base raised to the power of exponent. pow x y = x^y for positive integers x and y. Raises Invalid_argument if x = y = 0 or y < 0.
floor_div x n is integer division rounding towards negative infinity. It satisfies x = m * floor_div x n + rem x n.
range_by ~step i j iterates on integers from i to j included, where the difference between successive elements is step. Use a negative step for a decreasing list.
range i j iterates on integers from i to j included . It works both for decreasing and increasing ranges.
range' i j is like range but the second bound j is excluded. For instance range' 0 5 = Iter.of_list [0;1;2;3;4].
val random : t -> t random_genval random_small : t random_genval random_range : t -> t -> t random_genval of_string : string -> t optionof_string s is the safe version of of_string_exn. Like of_string_exn, but return None instead of raising.
val of_string_exn : string -> tof_string_exn s converts the given string s into a 64-bit integer. Alias to Int64.of_string. The string is read in decimal (by default, or if the string begins with 0u) or in hexadecimal, octal or binary if the string begins with 0x, 0o or 0b respectively.
The 0u prefix reads the input as an unsigned integer in the range [0, 2*CCInt64.max_int+1]. If the input exceeds CCInt64.max_int it is converted to the signed integer CCInt64.min_int + input - CCInt64.max_int - 1.
The _ (underscore) character can appear anywhere in the string and is ignored. Raise Failure "Int64.of_string" if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type int64.
val to_string_binary : t -> stringto_string_binary x returns the string representation of the integer x, in binary.
Infix operators
module Infix : sig ... endinclude module type of Infixx / y is the integer quotient of x and y. Integer division. Raise Division_by_zero if the second argument y is zero. This division rounds the real quotient of its arguments towards zero, as specified for Stdlib.(/).
x mod y is the integer remainder of x / y. If y <> zero, the result of x mod y satisfies the following properties: zero <= x mod y < abs y and x = ((x / y) * y) + (x mod y). If y = 0, x mod y raises Division_by_zero.
x lsl y shifts x to the left by y bits, filling in with zeroes. The result is unspecified if y < 0 or y >= 64.
x lsr y shifts x to the right by y bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of x. The result is unspecified if y < 0 or y >= 64.
x asr y shifts x to the right by y bits. This is an arithmetic shift: the sign bit of x is replicated and inserted in the vacated bits. The result is unspecified if y < 0 or y >= 64.
CCList.Assocval get : eq:( 'a -> 'a -> bool ) -> 'a -> ( 'a, 'b ) t -> 'b optionget ~eq k alist returns Some v if the given key k is present into alist, or None if not present.
val get_exn : eq:( 'a -> 'a -> bool ) -> 'a -> ( 'a, 'b ) t -> 'bget_exn ~eq k alist returns v if the element k is present into alist. Like get, but unsafe.
set ~eq k v alist adds the binding k, v into the list alist (erase it if already present).
val mem : ?eq:( 'a -> 'a -> bool ) -> 'a -> ( 'a, _ ) t -> boolmem ?eq k alist returns true iff k is a key in alist.
val update :
+ eq:( 'a -> 'a -> bool ) ->
+ f:( 'b option -> 'b option ) ->
+ 'a ->
+ ( 'a, 'b ) t ->
+ ( 'a, 'b ) tupdate ~eq ~f k alist updates alist on the key k, by calling f (get k alist) and removing k if it returns None, mapping k to v' if it returns Some v'.
remove ~eq k alist returns the alist without the first pair with key k, if any.
val keys : ( 'a, 'b ) t -> 'a listkeys alist returns a list of all keys of alist.
val values : ( 'a, 'b ) t -> 'b listvalues alist returns a list of all values of alist.
CCList.Infixl >|= f is the infix version of map with reversed arguments.
val (--) : int -> int -> int ti -- j is the infix alias for range. Bounds included.
val (--^) : int -> int -> int ti --^ j is the infix alias for range'. Second bound j excluded.
(and&) is combine_shortest. It allows to perform a synchronized product between two lists, stopping gently at the shortest. Usable both with let+ and let*.
# let f xs ys zs =
+ let+ x = xs
+ and& y = ys
+ and& z = zs in
+ x + y + z;;
+val f : int list -> int list -> int list -> int list = <fun>
+# f [1;2] [5;6;7] [10;10];;
+- : int list = [16; 18]CCList.Refval push : 'a t -> 'a -> unitpush rlist e adds an element e at the head of rlist.
val pop : 'a t -> 'a optionpop rlist removes and returns Some e (the first element of rlist) or None if the rlist is empty
val pop_exn : 'a t -> 'apop_exn rlist removes and returns the first element of rlist. Unsafe version of pop.
val create : unit -> 'a tcreate () creates a new empty reference list.
val clear : _ t -> unitclear rlist removes all elements of rlist.
val lift : ( 'a list -> 'b ) -> 'a t -> 'blift f rlist applies a list function f to the content of rlist.
val push_list : 'a t -> 'a list -> unitpush_list rlist l adds elements of the list l at the beginning of the list ref rlist. Elements at the end of the list l will be at the beginning of the list ref rlist.
Traverse.1-Mval return : 'a -> 'a treturn is the Monadic return.
CCList.TraverseThis allows the traversal of a 'a t list where _ t is also a monad.
For example, a 'a option list will be traversed by extracting a value from each option, returning Some [x1;…;x_n]; but if one of the option is None then the whole result is None.
Another example is with result: ('a, 'err) result list can be transformed into ('a list, 'err) result by returning the first error, or Ok [x1; …; xn] if all the elements were successful.
This describes the behavior of sequence_m; map_m is a combination of map and sequence_m; map_m_par is like map_m but useful for some pseudo monads like Lwt.
Fold a function with a monadic effect through a list.
map_m_par f (x :: l) is like map_m but f x and f l are evaluated "in parallel" before combining their result (for instance in Lwt).
Basically, when encoutering x :: tl, this computes f x and map_m_par f tl, and only then is M.(>>=) used to combine the two results into a new list.
CCListComplements to List
val empty : 'a tempty is [].
val is_empty : _ t -> boolis_empty l returns true iff l = [].
map f [a0; a1; …; an] applies function f in turn to a0; a1; …; an. Safe version of List.map.
append l1 l2 returns the list that is the concatenation of l1 and l2. Safe version of List.append.
cons' l x is the same as x :: l. This is convenient for fold functions such as List.fold_left or Array.fold_left.
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 l is preserved. Safe version of List.filter.
val fold_right : ( 'a -> 'b -> 'b ) -> 'a t -> 'b -> 'bfold_right f [a1; …; an] b is f a1 (f a2 ( … (f an b) … )). Safe version of List.fold_right.
val fold_while : ( 'a -> 'b -> 'a * [ `Stop | `Continue ] ) -> 'a -> 'b t -> 'afold_while f init l folds until a stop condition via ('a, `Stop) is indicated by the accumulator.
fold_map f init l is a fold_left-like function, but it also maps the list to another list.
fold_map_i f init l is a foldi-like function, but it also maps the list to another list.
val fold_on_map :
+ f:( 'a -> 'b ) ->
+ reduce:( 'acc -> 'b -> 'acc ) ->
+ 'acc ->
+ 'a list ->
+ 'accfold_on_map ~f ~reduce init l combines map f and fold_left reduce init in one operation.
scan_left f init l returns the list [init; f init x0; f (f init x0) x1; …] where x0, x1, etc. are the elements of l.
reduce f (hd::tl) returns Some (fold_left f hd tl). If l is empty, then None is returned.
reduce_exn is the unsafe version of reduce.
val fold_map2 :
+ ( 'acc -> 'a -> 'b -> 'acc * 'c ) ->
+ 'acc ->
+ 'a list ->
+ 'b list ->
+ 'acc * 'c listfold_map2 f init l1 l2 is to fold_map what List.map2 is to List.map.
val fold_filter_map :
+ ( 'acc -> 'a -> 'acc * 'b option ) ->
+ 'acc ->
+ 'a list ->
+ 'acc * 'b listfold_filter_map f init l is a fold_left-like function, but also generates a list of output in a way similar to filter_map.
val fold_filter_map_i :
+ ( 'acc -> int -> 'a -> 'acc * 'b option ) ->
+ 'acc ->
+ 'a list ->
+ 'acc * 'b listfold_filter_map_i f init l is a foldi-like function, but also generates a list of output in a way similar to filter_map.
fold_flat_map f init l is a fold_left-like function, but it also maps the list to a list of lists that is then flatten'd.
val fold_flat_map_i :
+ ( 'acc -> int -> 'a -> 'acc * 'b list ) ->
+ 'acc ->
+ 'a list ->
+ 'acc * 'b listfold_flat_map_i f init l is a fold_left-like function, but it also maps the list to a list of lists that is then flatten'd.
count p l counts how many elements of l satisfy predicate p.
count_true_false p l returns a pair (int1,int2) where int1 is the number of elements in l that satisfy the predicate p, and int2 the number of elements that do not satisfy p.
val init : int -> ( int -> 'a ) -> 'a tinit len f is f 0; f 1; …; f (len-1).
combine [a1; …; an] [b1; …; bn] is [(a1,b1); …; (an,bn)]. Transform two lists into a list of pairs. Like List.combine but tail-recursive.
val combine_gen : 'a list -> 'b list -> ('a * 'b) gencombine_shortest [a1; …; am] [b1; …; bn] is [(a1,b1); …; (am,bm)] if m <= n. Like combine but stops at the shortest list rather than raising.
split [(a1,b1); …; (an,bn)] is ([a1; …; an], [b1; …; bn]). Transform a list of pairs into a pair of lists. A tail-recursive version of List.split.
compare cmp l1 l2 compares the two lists l1 and l2 using the given comparison function cmp.
compare_lengths l1 l2 compare the lengths of the two lists l1 and l2. Equivalent to compare (length l1) (length l2) but more efficient.
val compare_length_with : 'a t -> int -> intcompare_length_with l x compares the length of the list l to an integer x. Equivalent to compare (length l) x but more efficient.
equal p l1 l2 returns true if l1 and l2 are equal.
flat_map f l maps and flattens at the same time (safe). Evaluation order is not guaranteed.
flat_map_i f l maps with index and flattens at the same time (safe). Evaluation order is not guaranteed.
flatten [l1]; [l2]; … concatenates a list of lists. Safe version of List.flatten.
product comb l1 l2 computes the cartesian product of the two lists, with the given combinator comb.
fold_product f init l1 l2 applies the function f with the accumulator init on all the pair of elements of l1 and l2. Fold on the cartesian product.
cartesian_product [[l1]; [l2]; …; [ln]] produces the cartesian product of this list of lists, by returning all the ways of picking one element per sublist. NOTE the order of the returned list is unspecified. For example:
# cartesian_product [[1;2];[3];[4;5;6]] |> sort =
+[[1;3;4];[1;3;5];[1;3;6];[2;3;4];[2;3;5];[2;3;6]];;
+# cartesian_product [[1;2];[];[4;5;6]] = [];;
+# cartesian_product [[1;2];[3];[4];[5];[6]] |> sort =
+[[1;3;4;5;6];[2;3;4;5;6]];;invariant: cartesian_product l = map_product id l.
map_product_l f l maps each element of l to a list of objects of type 'b using f. We obtain [l1; l2; …; ln] where length l=n and li : 'b list. Then, it returns all the ways of picking exactly one element per li.
diagonal l returns all pairs of distinct positions of the list l, that is the list of List.nth i l, List.nth j l if i < j.
val partition_map_either :
+ ( 'a -> ( 'b, 'c ) CCEither.t ) ->
+ 'a list ->
+ 'b list * 'c listpartition_map_either f l maps f on l and gather results in lists:
f x = Left y, adds y to the first list.f x = Right z, adds z to the second list.val partition_filter_map :
+ ( 'a -> [< `Left of 'b | `Right of 'c | `Drop ] ) ->
+ 'a list ->
+ 'b list * 'c listpartition_filter_map f l maps f on l and gather results in lists:
f x = `Left y, adds y to the first list.f x = `Right z, adds z to the second list.f x = `Drop, ignores x.val partition_map :
+ ( 'a -> [< `Left of 'b | `Right of 'c | `Drop ] ) ->
+ 'a list ->
+ 'b list * 'c listgroup_by ?hash ?eq l groups equal elements, regardless of their order of appearance. precondition: for any x and y, if eq x y then hash x=hash y must hold.
join ~join_row a b combines every element of a with every element of b using join_row. If join_row returns None, then the two elements do not combine. Assume that b allows for multiple iterations.
val join_by :
+ ?eq:( 'key -> 'key -> bool ) ->
+ ?hash:( 'key -> int ) ->
+ ( 'a -> 'key ) ->
+ ( 'b -> 'key ) ->
+ merge:( 'key -> 'a -> 'b -> 'c option ) ->
+ 'a t ->
+ 'b t ->
+ 'c tjoin_by ?eq ?hash key1 key2 ~merge la lb is a binary operation that takes two sequences a and b, projects their elements resp. with key1 and key2, and combine values (x,y) from (a,b) with the same key using merge. If merge returns None, the combination of values is discarded. precondition: for any x and y, if eq x y then hash x=hash y must hold.
val join_all_by :
+ ?eq:( 'key -> 'key -> bool ) ->
+ ?hash:( 'key -> int ) ->
+ ( 'a -> 'key ) ->
+ ( 'b -> 'key ) ->
+ merge:( 'key -> 'a list -> 'b list -> 'c option ) ->
+ 'a t ->
+ 'b t ->
+ 'c tjoin_all_by ?eq ?hash key1 key2 ~merge la lb is a binary operation that takes two sequences a and b, projects their elements resp. with key1 and key2, and, for each key k occurring in at least one of them:
l1 of elements of a that map to kl2 of elements of b that map to kmerge k l1 l2. If merge returns None, the combination of values is discarded, otherwise it returns Some c and c is inserted in the result.val group_join_by :
+ ?eq:( 'a -> 'a -> bool ) ->
+ ?hash:( 'a -> int ) ->
+ ( 'b -> 'a ) ->
+ 'a t ->
+ 'b t ->
+ ('a * 'b list) tgroup_join_by ?eq ?hash key la lb associates to every element x of the first sequence, all the elements y of the second sequence such that eq x (key y). Elements of the first sequences without corresponding values in the second one are mapped to [] precondition: for any x and y, if eq x y then hash x=hash y must hold.
val sublists_of_len :
+ ?last:( 'a list -> 'a list option ) ->
+ ?offset:int ->
+ int ->
+ 'a list ->
+ 'a list listsublists_of_len ?last ?offset n l returns sub-lists of l that have length n. By default, these sub-lists are non overlapping: sublists_of_len 2 [1;2;3;4;5;6] returns [1;2]; [3;4]; [5;6].
Examples:
sublists_of_len 2 [1;2;3;4;5;6] = [[1;2]; [3;4]; [5;6]].sublists_of_len 2 ~offset:3 [1;2;3;4;5;6] = [1;2];[4;5].sublists_of_len 3 ~last:CCOption.return [1;2;3;4] = [1;2;3];[4].sublists_of_len 2 [1;2;3;4;5] = [[1;2]; [3;4]].chunks n l returns consecutives chunks of size at most n from l. Each item of l will occur in exactly one chunk. Only the last chunk might be of length smaller than n. Invariant: (chunks n l |> List.flatten) = l.
intersperse x l inserts the element x between adjacent elements of the list l.
interleave [x1…xn] [y1…ym] is [x1;y1;x2;y2;…] and finishes with the suffix of the longest list.
val pure : 'a -> 'a tpure x is return x.
val mguard : bool -> unit tmguard c is pure () if c is true, [] otherwise. This is useful to define a list by comprehension, e.g.:
# let square_even xs =
+ let* x = xs in
+ let* () = mguard (x mod 2 = 0) in
+ return @@ x * x;;
+val square_even : int list -> int list = <fun>
+# square_even [1;2;4;3;5;2];;
+- : int list = [4; 16; 4]val return : 'a -> 'a treturn x is x.
take_drop n l returns l1, l2 such that l1 @ l2 = l and length l1 = min (length l) n.
take_while f l returns the longest prefix of l for which f is true.
drop_while f l drops the longest prefix of l for which f is true.
take_drop_while p l = take_while p l, drop_while p l.
last n l takes the last n elements of l (or less if l doesn't have that many elements).
val head_opt : 'a t -> 'a optionhead_opt l returns Some x (the first element of the list l) or None if the list l is empty.
tail_opt l returns Some l' (the given list l without its first element) or None if the list l is empty.
val last_opt : 'a t -> 'a optionlast_opt l returns Some x (the last element of l) or None if the list l is empty.
val find_pred : ( 'a -> bool ) -> 'a t -> 'a optionfind_pred p l finds the first element of l that satisfies p, or returns None if no element satisfies p.
val find_pred_exn : ( 'a -> bool ) -> 'a t -> 'afind_pred_exn p l is the unsafe version of find_pred.
val find_map : ( 'a -> 'b option ) -> 'a t -> 'b optionfind_map f l traverses l, applying f to each element. If for some element x, f x = Some y, then Some y is returned. Otherwise the call returns None.
val find_mapi : ( int -> 'a -> 'b option ) -> 'a t -> 'b optionfind_mapi f l is like find_map, but also pass the index to the predicate function.
val find_idx : ( 'a -> bool ) -> 'a t -> (int * 'a) optionfind_idx p x returns Some (i,x) where x is the i-th element of l, and p x holds. Otherwise returns None.
remove ~eq ~key l removes every instance of key from l. Tail-recursive.
filter_map f l is the sublist of l containing only elements for which f returns Some e. Map and remove elements at the same time.
keep_some l retains only elements of the form Some x. Like filter_map CCFun.id.
all_some l returns Some l' if all elements of l are of the form Some x, or None otherwise.
all_ok l returns Ok l' if all elements of l are of the form Ok x, or Error e otherwise (with the first error met).
sorted_mem ~cmp x l and mem x l give the same result for any sorted list l, but potentially more efficiently.
sorted_merge ~cmp l1 l2 merges elements from both sorted list using the given comparison function cmp.
sorted_diff ~cmp l1 l2 returns the elements in l1 that are not in l2. Both lists are assumed to be sorted with respect to cmp and duplicate elements in the input lists are treated individually; for example, sorted_diff ~cmp [1;1;1;2;2;3] [1;2;2] would be [1;1;3]. It is the left inverse of sorted_merge; that is, sorted_diff ~cmp (sorted_merge ~cmp l1 l2) l2 is always equal to l1 for sorted lists l1 and l2.
sort_uniq ~cmp l sorts the list l using the given comparison function cmp and remove duplicate elements.
sorted_merge_uniq ~cmp l1 l2 merges the sorted lists l1 and l2 and removes duplicates.
sorted_diff_uniq ~cmp l1 l2 collects the elements in l1 that are not in l2 and then remove duplicates. Both lists are assumed to be sorted with respect to cmp and duplicate elements in the input lists are treated individually; for example, sorted_diff_uniq ~cmp [1;1;1;2;2] [1;2;2;2] would be [1]. sorted_diff_uniq ~cmp l1 l2 and uniq_succ ~eq (sorted_diff ~cmp l1 l2) always give the same result for sorted l1 and l2 and compatible cmp and eq.
is_sorted ~cmp l returns true iff l is sorted (according to given order).
sorted_insert ~cmp ?uniq x l inserts x into l such that, if l was sorted, then sorted_insert x l is sorted too.
sorted_remove ~cmp x l removes x from a sorted list l such that the return value is sorted too. By default, it is the left inverse of sorted_insert; that is, sorted_remove ~cmp x (sorted_insert ~cmp x l) is equal to l for any sorted list l.
uniq_succ ~eq l removes duplicate elements that occur one next to the other. Examples: uniq_succ ~eq:(=) [1;2;1] = [1;2;1]. uniq_succ ~eq:(=) [1;1;2] = [1;2].
group_succ ~eq l groups together consecutive elements that are equal according to eq.
mapi f l is like map, but the function f is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
val iteri : ( int -> 'a -> unit ) -> 'a t -> unititeri f l is like iter, but the function f is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
iteri2 f l1 l2 applies f to the two lists l1 and l2 simultaneously. The integer passed to f indicates the index of element.
val foldi : ( 'b -> int -> 'a -> 'b ) -> 'b -> 'a t -> 'bfoldi f init l is like fold but it also passes in the index of each element, from 0 to length l - 1 as additional argument to the folded function f. Tail-recursive.
foldi2 f init l1 l2 folds on the two lists l1 and l2, with index of each element passed to the function f. Computes f(… (f init i_0 l1_0 l2_0) …) i_n l1_n l2_n .
val get_at_idx : int -> 'a t -> 'a optionget_at_idx i l returns Some i-th element of the given list l or None if the list l is too short. If the index is negative, it will get element starting from the end of the list l.
val nth_opt : 'a t -> int -> 'a optionnth_opt l n returns Some n-th element of l. Safe version of nth.
val get_at_idx_exn : int -> 'a t -> 'aget_at_idx_exn i l gets the i-th element of l, or
set_at_idx i x l replaces the i-th element with x (removes the old one), or does nothing if index is too high. If the index is negative, it will set element starting from the end of the list.
insert_at_idx i x l inserts x at i-th position, between the two existing elements. If the index is too high, append at the end of the list. If the index is negative, it will insert element starting from the end of the list.
remove_at_idx i l removes element at given index i. Does nothing if the index is too high. If the index is negative, it will remove element starting from the end of the list.
Those operations maintain the invariant that the list does not contain duplicates (if it already satisfies it).
add_nodup ~eq x set adds x to set if it was not already present. Linear time.
remove_one ~eq x set removes one occurrence of x from set. Linear time.
val mem : ?eq:( 'a -> 'a -> bool ) -> 'a -> 'a t -> boolmem ?eq x l is true iff x is equal to an element of l. A comparator function eq can be provided. Linear time.
subset ~eq l1 l2 tests if all elements of the list l1 are contained in the list l2 by applying eq.
uniq ~eq l removes duplicates in l w.r.t the equality predicate eq. Complexity is quadratic in the length of the list, but the order of elements is preserved. If you wish for a faster de-duplication but do not care about the order, use sort_uniq.
union ~eq l1 l2 is the union of the lists l1 and l2 w.r.t. the equality predicate eq. Complexity is product of length of inputs.
inter ~eq l1 l2 is the intersection of the lists l1 and l2 w.r.t. the equality predicate eq. Complexity is product of length of inputs.
val range_by : step:int -> int -> int -> int trange_by ~step i j iterates on integers from i to j included, where the difference between successive elements is step. Use a negative step for a decreasing list.
val range : int -> int -> int trange i j iterates on integers from i to j included. It works both for decreasing and increasing ranges.
val range' : int -> int -> int trange' i j is like range but the second bound j is excluded. For instance range' 0 5 = [0;1;2;3;4].
val replicate : int -> 'a -> 'a treplicate n x replicates the given element x n times.
module Assoc : sig ... endval assoc : eq:( 'a -> 'a -> bool ) -> 'a -> ('a * 'b) t -> 'bassoc ~eq k alist returns the value v associated with key k in alist. Like Assoc.get_exn.
val assoc_opt : eq:( 'a -> 'a -> bool ) -> 'a -> ('a * 'b) t -> 'b optionassoc_opt ~eq k alist returns Some v if the given key k is present into alist, or None if not present. Like Assoc.get.
val assq_opt : 'a -> ('a * 'b) t -> 'b optionassq_opt k alist returns Some v if the given key k is present into alist. Like Assoc.assoc_opt but use physical equality instead of structural equality to compare keys. Safe version of assq.
val mem_assoc : ?eq:( 'a -> 'a -> bool ) -> 'a -> ('a * _) t -> boolmem_assoc ?eq k alist returns true iff k is a key in alist. Like Assoc.mem.
remove_assoc ~eq k alist returns the alist without the first pair with key k, if any. Like Assoc.remove.
module Ref : sig ... endmodule type MONAD = sig ... endval random : 'a random_gen -> 'a t random_genval random_non_empty : 'a random_gen -> 'a t random_genval random_len : int -> 'a random_gen -> 'a t random_genval random_choose : 'a t -> 'a random_genrandom_choose l randomly chooses an element in the list l.
val random_sequence : 'a random_gen t -> 'a t random_genval to_string :
+ ?start:string ->
+ ?stop:string ->
+ ?sep:string ->
+ ( 'a -> string ) ->
+ 'a t ->
+ stringto_string ?start ?stop ?sep item_to_string l prints l to a string using sep as a separator between elements of l.
val to_seq : 'a t -> 'a Stdlib.Seq.tto_seq l returns a Seq.t of the elements of the list l. Renamed from to_std_seq since 3.0.
of_iter iter builds a list from a given iter. In the result, elements appear in the same order as they did in the source iter.
val of_seq_rev : 'a Stdlib.Seq.t -> 'a tof_seq_rev seq builds a list from a given Seq.t, in reverse order. Renamed from to_std_seq_rev since 3.0.
val of_seq : 'a Stdlib.Seq.t -> 'a tof_seq seq builds a list from a given Seq.t. In the result, elements appear in the same order as they did in the source Seq.t. Renamed from of_std_seq since 3.0.
of_gen gen builds a list from a given gen. In the result, elements appear in the same order as they did in the source gen.
It is convenient to open CCList.Infix to access the infix operators without cluttering the scope too much.
module Infix : sig ... endinclude module type of Infixl >|= f is the infix version of map with reversed arguments.
val (--) : int -> int -> int ti -- j is the infix alias for range. Bounds included.
val (--^) : int -> int -> int ti --^ j is the infix alias for range'. Second bound j excluded.
(and&) is combine_shortest. It allows to perform a synchronized product between two lists, stopping gently at the shortest. Usable both with let+ and let*.
# let f xs ys zs =
+ let+ x = xs
+ and& y = ys
+ and& z = zs in
+ x + y + z;;
+val f : int list -> int list -> int list -> int list = <fun>
+# f [1;2] [5;6;7] [10;10];;
+- : int list = [16; 18]CCList.MONADval return : 'a -> 'a treturn is the Monadic return.
CCListLabels.Assocval get : eq:( 'a -> 'a -> bool ) -> 'a -> ( 'a, 'b ) t -> 'b optionget ~eq k alist returns Some v if the given key k is present into alist, or None if not present.
val get_exn : eq:( 'a -> 'a -> bool ) -> 'a -> ( 'a, 'b ) t -> 'bget_exn ~eq k alist returns v if the element k is present into alist. Like get, but unsafe.
set ~eq k v alist adds the binding k, v into the list alist (erase it if already present).
val mem : ?eq:( 'a -> 'a -> bool ) -> 'a -> ( 'a, _ ) t -> boolmem ?eq k alist returns true iff k is a key in alist.
val update :
+ eq:( 'a -> 'a -> bool ) ->
+ f:( 'b option -> 'b option ) ->
+ 'a ->
+ ( 'a, 'b ) t ->
+ ( 'a, 'b ) tupdate ~eq ~f k alist updates alist on the key k, by calling f (get alist k) and removing k if it returns None, mapping k to v' if it returns Some v'.
remove ~eq k alist returns the alist without the first pair with key k, if any.
val keys : ( 'a, 'b ) t -> 'a listkeys alist returns a list of all keys of alist.
val values : ( 'a, 'b ) t -> 'b listvalues alist returns a list of all values of alist.
CCListLabels.Infixl >|= f is the infix version of map with reversed arguments.
l1 @ l2 concatenates two lists l1 and l2. As append.
funs <*> l is product (fun f x -> f x) funs l.
val (--) : int -> int -> int CCList.ti -- j is the infix alias for range. Bounds included.
val (--^) : int -> int -> int CCList.ti --^ j is the infix alias for range'. Second bound j excluded.
(and&) is combine_shortest. It allows to perform a synchronized product between two lists, stopping gently at the shortest. Usable both with let+ and let*.
# let f xs ys zs =
+ let+ x = xs
+ and& y = ys
+ and& z = zs in
+ x + y + z;;
+val f : int list -> int list -> int list -> int list = <fun>
+# f [1;2] [5;6;7] [10;10];;
+- : int list = [16; 18]CCListLabels.Refval push : 'a t -> 'a -> unitpush rlist e adds an element e at the head of rlist.
val pop : 'a t -> 'a optionpop rlist removes and returns Some e (the first element of rlist) or None if the rlist is empty
val pop_exn : 'a t -> 'apop_exn rlist removes and returns the first element of rlist. Unsafe version of pop.
val create : unit -> 'a tcreate () creates a new empty reference list.
val clear : _ t -> unitclear rlist removes all elements of rlist.
val lift : ( 'a list -> 'b ) -> 'a t -> 'blift f rlist applies a list function f to the content of rlist.
val push_list : 'a t -> 'a list -> unitpush_list rlist l adds elements of the list l at the beginning of the list ref rlist. Elements at the end of the list l will be at the beginning of the list ref rlist.
Traverse.1-Mval return : 'a -> 'a treturn is the Monadic return.
CCListLabels.TraverseCCListLabelsComplements to ListLabels
include module type of Stdlib.ListLabelsval empty : 'a tempty is [].
val is_empty : _ t -> boolis_empty l returns true iff l = [].
map ~f [a0; a1; …; an] applies function f in turn to [a0; a1; …; an]. Safe version of List.map.
append l1 l2 returns the list that is the concatenation of l1 and l2. Safe version of List.append.
cons' l x is the same as x :: l. This is convenient for fold functions such as List.fold_left or Array.fold_left.
filter ~f l returns all the elements of the list l that satisfy the predicate f. The order of the elements in the input list l is preserved. Safe version of List.filter.
val fold_right : f:( 'a -> 'b -> 'b ) -> 'a t -> init:'b -> 'bfold_right ~f [a1; …; an] ~init is f a1 (f a2 ( … (f an init) … )). Safe version of List.fold_right.
val fold_while :
+ f:( 'a -> 'b -> 'a * [ `Stop | `Continue ] ) ->
+ init:'a ->
+ 'b t ->
+ 'afold_while ~f ~init l folds until a stop condition via ('a, `Stop) is indicated by the accumulator.
fold_map ~f ~init l is a fold_left-like function, but it also maps the list to another list.
val fold_map_i :
+ f:( 'acc -> int -> 'a -> 'acc * 'b ) ->
+ init:'acc ->
+ 'a list ->
+ 'acc * 'b listfold_map_i ~f ~init l is a foldi-like function, but it also maps the list to another list.
val fold_on_map :
+ f:( 'a -> 'b ) ->
+ reduce:( 'acc -> 'b -> 'acc ) ->
+ init:'acc ->
+ 'a list ->
+ 'accfold_on_map ~f ~reduce ~init l combines map ~f and fold_left ~reduce ~init in one operation.
scan_left ~f ~init l returns the list [init; f init x0; f (f init x0) x1; …] where x0, x1, etc. are the elements of l.
reduce f (hd::tl) returns Some (fold_left f hd tl). If l is empty, then None is returned.
reduce_exn is the unsafe version of reduce.
val fold_map2 :
+ f:( 'acc -> 'a -> 'b -> 'acc * 'c ) ->
+ init:'acc ->
+ 'a list ->
+ 'b list ->
+ 'acc * 'c listfold_map2 ~f ~init l1 l2 is to fold_map what List.map2 is to List.map.
val fold_filter_map :
+ f:( 'acc -> 'a -> 'acc * 'b option ) ->
+ init:'acc ->
+ 'a list ->
+ 'acc * 'b listfold_filter_map ~f ~init l is a fold_left-like function, but also generates a list of output in a way similar to filter_map.
val fold_filter_map_i :
+ f:( 'acc -> int -> 'a -> 'acc * 'b option ) ->
+ init:'acc ->
+ 'a list ->
+ 'acc * 'b listfold_filter_map_i ~f ~init l is a foldi-like function, but also generates a list of output in a way similar to filter_map.
val fold_flat_map :
+ f:( 'acc -> 'a -> 'acc * 'b list ) ->
+ init:'acc ->
+ 'a list ->
+ 'acc * 'b listfold_flat_map ~f ~init l is a fold_left-like function, but it also maps the list to a list of lists that is then flatten'd.
val fold_flat_map_i :
+ f:( 'acc -> int -> 'a -> 'acc * 'b list ) ->
+ init:'acc ->
+ 'a list ->
+ 'acc * 'b listfold_flat_map_i ~f ~init l is a fold_left-like function, but it also maps the list to a list of lists that is then flatten'd.
count ~f l counts how many elements of l satisfy predicate f.
count_true_false ~f l returns a pair (int1,int2) where int1 is the number of elements in l that satisfy the predicate f, and int2 the number of elements that do not satisfy f.
val init : int -> f:( int -> 'a ) -> 'a tinit len ~f is f 0; f 1; …; f (len-1).
combine [a1; …; an] [b1; …; bn] is [(a1,b1); …; (an,bn)]. Transform two lists into a list of pairs. Like List.combine but tail-recursive.
val combine_gen : 'a list -> 'b list -> ('a * 'b) gencombine_shortest [a1; …; am] [b1; …; bn] is [(a1,b1); …; (am,bm)] if m <= n. Like combine but stops at the shortest list rather than raising.
split [(a1,b1); …; (an,bn)] is ([a1; …; an], [b1; …; bn]). Transform a list of pairs into a pair of lists. A tail-recursive version of List.split.
compare cmp l1 l2 compares the two lists l1 and l2 using the given comparison function cmp.
compare_lengths l1 l2 compare the lengths of the two lists l1 and l2. Equivalent to compare (length l1) (length l2) but more efficient.
val compare_length_with : 'a t -> int -> intcompare_length_with l x compares the length of the list l to an integer x. Equivalent to compare (length l) x but more efficient.
equal p l1 l2 returns true if l1 and l2 are equal.
flat_map ~f l maps and flattens at the same time (safe). Evaluation order is not guaranteed.
flat_map_i ~f l maps with index and flattens at the same time (safe). Evaluation order is not guaranteed.
flatten [l1]; [l2]; … concatenates a list of lists. Safe version of List.flatten.
product ~f l1 l2 computes the cartesian product of the two lists, with the given combinator f.
fold_product ~f ~init l1 l2 applies the function f with the accumulator init on all the pair of elements of l1 and l2. Fold on the cartesian product.
cartesian_product [[l1];[l2]; …; [ln]] produces the cartesian product of this list of lists, by returning all the ways of picking one element per sublist. NOTE the order of the returned list is unspecified. For example:
# cartesian_product [[1;2];[3];[4;5;6]] |> sort =
+[[1;3;4];[1;3;5];[1;3;6];[2;3;4];[2;3;5];[2;3;6]];;
+# cartesian_product [[1;2];[];[4;5;6]] = [];;
+# cartesian_product [[1;2];[3];[4];[5];[6]] |> sort =
+[[1;3;4;5;6];[2;3;4;5;6]];;invariant: cartesian_product l = map_product id l.
map_product_l ~f l maps each element of l to a list of objects of type 'b using f. We obtain [l1; l2; …; ln] where length l=n and li : 'b list. Then, it returns all the ways of picking exactly one element per li.
diagonal l returns all pairs of distinct positions of the list l, that is the list of List.nth i l, List.nth j l if i < j.
val partition_map_either :
+ f:( 'a -> ( 'b, 'c ) CCEither.t ) ->
+ 'a list ->
+ 'b list * 'c listpartition_map_either ~f l maps f on l and gather results in lists:
f x = Left y, adds y to the first list.f x = Right z, adds z to the second list.val partition_filter_map :
+ f:( 'a -> [< `Left of 'b | `Right of 'c | `Drop ] ) ->
+ 'a list ->
+ 'b list * 'c listpartition_filter_map ~f l maps f on l and gather results in lists:
f x = `Left y, adds y to the first list.f x = `Right z, adds z to the second list.f x = `Drop, ignores x.val partition_map :
+ f:( 'a -> [< `Left of 'b | `Right of 'c | `Drop ] ) ->
+ 'a list ->
+ 'b list * 'c listgroup_by ?hash ?eq l groups equal elements, regardless of their order of appearance. precondition: for any x and y, if eq x y then hash x = hash y must hold.
join ~join_row a b combines every element of a with every element of b using join_row. If join_row returns None, then the two elements do not combine. Assume that b allows for multiple iterations.
val join_by :
+ ?eq:( 'key -> 'key -> bool ) ->
+ ?hash:( 'key -> int ) ->
+ ( 'a -> 'key ) ->
+ ( 'b -> 'key ) ->
+ merge:( 'key -> 'a -> 'b -> 'c option ) ->
+ 'a t ->
+ 'b t ->
+ 'c tjoin_by ?eq ?hash key1 key2 ~merge la lb is a binary operation that takes two sequences a and b, projects their elements resp. with key1 and key2, and combine values (x,y) from (a,b) with the same key using merge. If merge returns None, the combination of values is discarded. precondition: for any x and y, if eq x y then hash x = hash y must hold.
val join_all_by :
+ ?eq:( 'key -> 'key -> bool ) ->
+ ?hash:( 'key -> int ) ->
+ ( 'a -> 'key ) ->
+ ( 'b -> 'key ) ->
+ merge:( 'key -> 'a list -> 'b list -> 'c option ) ->
+ 'a t ->
+ 'b t ->
+ 'c tjoin_all_by ?eq ?hash key1 key2 ~merge la lb is a binary operation that takes two sequences a and b, projects their elements resp. with key1 and key2, and, for each key k occurring in at least one of them:
l1 of elements of a that map to kl2 of elements of b that map to kmerge k l1 l2. If merge returns None, the combination of values is discarded, otherwise it returns Some c and c is inserted in the result.val group_join_by :
+ ?eq:( 'a -> 'a -> bool ) ->
+ ?hash:( 'a -> int ) ->
+ ( 'b -> 'a ) ->
+ 'a t ->
+ 'b t ->
+ ('a * 'b list) tgroup_join_by ?eq ?hash key la lb associates to every element x of the first sequence, all the elements y of the second sequence such that eq x (key y). Elements of the first sequences without corresponding values in the second one are mapped to [] precondition: for any x and y, if eq x y then hash x = hash y must hold.
val sublists_of_len :
+ ?last:( 'a list -> 'a list option ) ->
+ ?offset:int ->
+ len:int ->
+ 'a list ->
+ 'a list listsublists_of_len ?last ?offset n l returns sub-lists of l that have length n. By default, these sub-lists are non overlapping: sublists_of_len 2 [1;2;3;4;5;6] returns [1;2]; [3;4]; [5;6].
Examples:
sublists_of_len 2 [1;2;3;4;5;6] = [[1;2]; [3;4]; [5;6]].sublists_of_len 2 ~offset:3 [1;2;3;4;5;6] = [1;2];[4;5].sublists_of_len 3 ~last:CCOption.return [1;2;3;4] = [1;2;3];[4].sublists_of_len 2 [1;2;3;4;5] = [[1;2]; [3;4]].chunks n l returns consecutives chunks of size at most n from l. Each item of l will occur in exactly one chunk. Only the last chunk might be of length smaller than n. Invariant: (chunks n l |> List.flatten) = l.
intersperse ~x l inserts the element x between adjacent elements of the list l.
interleave [x1…xn] [y1…ym] is [x1,y1,x2,y2,…] and finishes with the suffix of the longest list.
val pure : 'a -> 'a tpure x is return x.
val mguard : bool -> unit tmguard c is pure () if c is true, [] otherwise. This is useful to define a list by comprehension, e.g.:
# let square_even xs =
+ let* x = xs in
+ let* () = mguard (x mod 2 = 0) in
+ return @@ x * x;;
+val square_even : int list -> int list = <fun>
+# square_even [1;2;4;3;5;2];;
+- : int list = [4; 16; 4]val return : 'a -> 'a treturn x is x.
take_drop n l returns l1, l2 such that l1 @ l2 = l and length l1 = min (length l) n.
take_while ~f l returns the longest prefix of l for which f is true.
drop_while ~f l drops the longest prefix of l for which f is true.
take_drop_while ~f l = take_while ~f l, drop_while ~f l.
last n l takes the last n elements of l (or less if l doesn't have that many elements).
val head_opt : 'a t -> 'a optionhead_opt l returns Some x (the first element of the list l) or None if the list l is empty.
tail_opt l returns Some l' (the given list l without its first element) or None if the list l is empty.
val last_opt : 'a t -> 'a optionlast_opt l returns Some x (the last element of l) or None if the list l is empty.
val find_pred : f:( 'a -> bool ) -> 'a t -> 'a optionfind_pred ~f l finds the first element of l that satisfies f, or returns None if no element satisfies f.
val find_pred_exn : f:( 'a -> bool ) -> 'a t -> 'afind_pred_exn ~f l is the unsafe version of find_pred.
val find_map : f:( 'a -> 'b option ) -> 'a t -> 'b optionfind_map ~f l traverses l, applying f to each element. If for some element x, f x = Some y, then Some y is returned. Otherwise the call returns None.
val find_mapi : f:( int -> 'a -> 'b option ) -> 'a t -> 'b optionfind_mapi ~f l is like find_map, but also pass the index to the predicate function.
val find_idx : f:( 'a -> bool ) -> 'a t -> (int * 'a) optionfind_idx ~f x returns Some (i,x) where x is the i-th element of l, and f x holds. Otherwise returns None.
remove ~eq ~key l removes every instance of key from l. Tail-recursive.
filter_map ~f l is the sublist of l containing only elements for which f returns Some e. Map and remove elements at the same time.
keep_some l retains only elements of the form Some x. Like filter_map CCFun.id.
all_some l returns Some l' if all elements of l are of the form Some x, or None otherwise.
all_ok l returns Ok l' if all elements of l are of the form Ok x, or Error e otherwise (with the first error met).
sorted_mem ~cmp x l and mem x l give the same result for any sorted list l, but potentially more efficiently.
sorted_merge ~cmp l1 l2 merges elements from both sorted list using the given comparison function cmp.
sorted_diff ~cmp l1 l2 returns the elements in l1 that are not in l2. Both lists are assumed to be sorted with respect to cmp and duplicate elements in the input lists are treated individually; for example, sorted_diff ~cmp [1;1;1;2;2;3] [1;2;2] would be [1;1;3]. It is the left inverse of sorted_merge; that is, sorted_diff ~cmp (sorted_merge ~cmp l1 l2) l2 is always equal to l1 for sorted lists l1 and l2.
sort_uniq ~cmp l sorts the list l using the given comparison function cmp and remove duplicate elements.
sorted_merge_uniq ~cmp l1 l2 merges the sorted lists l1 and l2 and removes duplicates.
sorted_diff_uniq ~cmp l1 l2 collects the elements in l1 that are not in l2 and then remove duplicates. Both lists are assumed to be sorted with respect to cmp and duplicate elements in the input lists are treated individually; for example, sorted_diff_uniq ~cmp [1;1;1;2;2] [1;2;2;2] would be [1]. sorted_diff_uniq ~cmp l1 l2 and uniq_succ ~eq (sorted_diff ~cmp l1 l2) always give the same result for sorted l1 and l2 and compatible cmp and eq.
is_sorted ~cmp l returns true iff l is sorted (according to given order).
sorted_insert ~cmp ?uniq x l inserts x into l such that, if l was sorted, then sorted_insert x l is sorted too.
sorted_remove ~cmp x l removes x from a sorted list l such that the return value is sorted too. By default, it is the left inverse of sorted_insert; that is, sorted_remove ~cmp x (sorted_insert ~cmp x l) is equal to l for any sorted list l.
uniq_succ ~eq l removes duplicate elements that occur one next to the other. Examples: uniq_succ [1;2;1] = [1;2;1]. uniq_succ [1;1;2] = [1;2].
group_succ ~eq l groups together consecutive elements that are equal according to eq.
mapi ~f l is like map, but the function f is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
val iteri : f:( int -> 'a -> unit ) -> 'a t -> unititeri ~f l is like iter, but the function f is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
iteri2 ~f l1 l2 applies f to the two lists l1 and l2 simultaneously. The integer passed to f indicates the index of element.
val foldi : f:( 'b -> int -> 'a -> 'b ) -> init:'b -> 'a t -> 'bfoldi ~f ~init l is like fold but it also passes in the index of each element, from 0 to length l - 1 as additional argument to the folded function f. Tail-recursive.
foldi2 ~f ~init l1 l2 folds on the two lists l1 and l2, with index of each element passed to the function f. Computes f(… (f init i_0 l1_0 l2_0) …) i_n l1_n l2_n .
val get_at_idx : int -> 'a t -> 'a optionget_at_idx i l returns Some i-th element of the given list l or None if the list l is too short. If the index is negative, it will get element starting from the end of the list l.
val nth_opt : 'a t -> int -> 'a optionnth_opt l n returns Some n-th element of l. Safe version of nth.
val get_at_idx_exn : int -> 'a t -> 'aget_at_idx_exn i l gets the i-th element of l, or
set_at_idx i x l replaces the i-th element with x (removes the old one), or does nothing if index is too high. If the index is negative, it will set element starting from the end of the list.
insert_at_idx i x l inserts x at i-th position, between the two existing elements. If the index is too high, append at the end of the list. If the index is negative, it will insert element starting from the end of the list.
remove_at_idx i l removes element at given index i. Does nothing if the index is too high. If the index is negative, it will remove element starting from the end of the list.
Those operations maintain the invariant that the list does not contain duplicates (if it already satisfies it).
add_nodup ~eq x set adds x to set if it was not already present. Linear time.
remove_one ~eq x set removes one occurrence of x from set. Linear time.
val mem : ?eq:( 'a -> 'a -> bool ) -> 'a -> 'a t -> boolmem ?eq x l is true iff x is equal to an element of l. A comparator function eq can be provided. Linear time.
subset ~eq l1 l2 tests if all elements of the list l1 are contained in the list l2 by applying eq.
uniq ~eq l removes duplicates in l w.r.t the equality predicate eq. Complexity is quadratic in the length of the list, but the order of elements is preserved. If you wish for a faster de-duplication but do not care about the order, use sort_uniq.
union ~eq l1 l2 is the union of the lists l1 and l2 w.r.t. the equality predicate eq. Complexity is product of length of inputs.
inter ~eq l1 l2 is the intersection of the lists l1 and l2 w.r.t. the equality predicate eq. Complexity is product of length of inputs.
val range_by : step:int -> int -> int -> int trange_by ~step i j iterates on integers from i to j included, where the difference between successive elements is step. Use a negative step for a decreasing list.
val range : int -> int -> int trange i j iterates on integers from i to j included. It works both for decreasing and increasing ranges.
val range' : int -> int -> int trange' i j is like range but the second bound j is excluded. For instance range' 0 5 = [0;1;2;3;4].
val replicate : int -> 'a -> 'a treplicate n x replicates the given element x n times.
module Assoc : sig ... endval assoc : eq:( 'a -> 'a -> bool ) -> 'a -> ('a * 'b) t -> 'bassoc ~eq k alist returns the value v associated with key k in alist. Like Assoc.get_exn.
val assoc_opt : eq:( 'a -> 'a -> bool ) -> 'a -> ('a * 'b) t -> 'b optionassoc_opt ~eq k alist returns Some v if the given key k is present into alist, or None if not present. Like Assoc.get.
val assq_opt : 'a -> ('a * 'b) t -> 'b optionassq_opt k alist returns Some v if the given key k is present into alist. Like Assoc.assoc_opt but use physical equality instead of structural equality to compare keys. Safe version of assq.
val mem_assoc : ?eq:( 'a -> 'a -> bool ) -> 'a -> ('a * _) t -> boolmem_assoc ?eq k alist returns true iff k is a key in alist. Like Assoc.mem.
remove_assoc ~eq k alist returns the alist without the first pair with key k, if any. Like Assoc.remove.
module Ref : sig ... endmodule type MONAD = sig ... endval random : 'a random_gen -> 'a t random_genval random_non_empty : 'a random_gen -> 'a t random_genval random_len : int -> 'a random_gen -> 'a t random_genval random_choose : 'a t -> 'a random_genrandom_choose l randomly chooses an element in the list l.
val random_sequence : 'a random_gen t -> 'a t random_genval to_string :
+ ?start:string ->
+ ?stop:string ->
+ ?sep:string ->
+ ( 'a -> string ) ->
+ 'a t ->
+ stringto_string ?start ?stop ?sep item_to_string l print l to a string using sep as a separator between elements of l.
val to_seq : 'a t -> 'a Stdlib.Seq.tto_seq l returns a Seq.t of the elements of the list l. Renamed from to_std_seq since 3.0.
of_iter iter builds a list from a given iter. In the result, elements appear in the same order as they did in the source iter.
val of_seq_rev : 'a Stdlib.Seq.t -> 'a tof_seq_rev seq builds a list from a given Seq.t, in reverse order. Renamed from of_std_seq_rev since 3.0.
val of_seq : 'a Stdlib.Seq.t -> 'a tof_seq seq builds a list from a given Seq.t. In the result, elements appear in the same order as they did in the source Seq.t. Renamed from of_std_seq since 3.0.
of_gen gen builds a list from a given gen. In the result, elements appear in the same order as they did in the source gen.
It is convenient to openCCList.Infix to access the infix operators without cluttering the scope too much.
module Infix : module type of CCList.Infixinclude module type of Infixl >|= f is the infix version of map with reversed arguments.
l1 @ l2 concatenates two lists l1 and l2. As append.
funs <*> l is product (fun f x -> f x) funs l.
val (--) : int -> int -> int CCList.ti -- j is the infix alias for range. Bounds included.
val (--^) : int -> int -> int CCList.ti --^ j is the infix alias for range'. Second bound j excluded.
(and&) is combine_shortest. It allows to perform a synchronized product between two lists, stopping gently at the shortest. Usable both with let+ and let*.
# let f xs ys zs =
+ let+ x = xs
+ and& y = ys
+ and& z = zs in
+ x + y + z;;
+val f : int list -> int list -> int list -> int list = <fun>
+# f [1;2] [5;6;7] [10;10];;
+- : int list = [16; 18]CCListLabels.MONADval return : 'a -> 'a treturn is the Monadic return.
CCMap.Makeget k m returns Some v if the current binding of k in m is v, or None if the key k is not present. Safe version of find.
get_or k m ~default returns the value associated to k if present, and returns default otherwise (if k doesn't belong in m).
update k f m calls f (Some v) if find k m = v, otherwise it calls f None. In any case, if the result is None k is removed from m, and if the result is Some v' then add k v' m is returned.
choose_opt m returns one binding of the given map m, or None if m is empty. Safe version of choose.
min_binding_opt m returns the smallest binding of the given map m, or None if m is empty. Safe version of min_binding.
max_binding_opt m returns the largest binding of the given map m, or None if m is empty. Safe version of max_binding.
find_opt k m returns Some v if the current binding of k in m is v, or None if the key k is not present. Safe version of find.
find_first f m where f is a monotonically increasing function, returns the binding of m with the lowest key k such that f k, or raises Not_found if no such key exists. See Map.S.find_first.
find_first_opt f m where f is a monotonically increasing function, returns an option containing the binding of m with the lowest key k such that f k, or None if no such key exists. Safe version of find_first.
val merge_safe :
+ f:( key -> [ `Left of 'a | `Right of 'b | `Both of 'a * 'b ] -> 'c option ) ->
+ 'a t ->
+ 'b t ->
+ 'c tmerge_safe ~f a b merges the maps a and b together.
add_seq m seq adds the given Seq.t of bindings to the map m. Like add_list. Renamed from add_std_seq since 3.0.
add_seq ~f m l adds the given seq l of bindings to the map m, using f to combine values that have the same key. If a key occurs several times, all its bindings are combined using the function f, with f key v1 v2 being called with v1 occurring later in the seq than v2.
of_seq seq builds a map from the given Seq.t of bindings. Like of_list. Renamed from of_std_seq since 3.0.
of_seq_with ~f l builds a map from the given seq l of bindings k_i -> v_i, added in order using add. If a key occurs several times, all its bindings are combined using the function f, with f key v1 v2 being called with v1 occurring later in the seq than v2.
add_iter m iter adds the given iter of bindings to the map m. Like add_list.
add_iter ~f m l adds the given iter l of bindings to the map m, using f to combine values that have the same key. If a key occurs several times, all its bindings are combined using the function f, with f key v1 v2 being called with v1 occurring later in the seq than v2.
of_iter iter builds a map from the given iter of bindings. Like of_list.
of_iter_with ~f l builds a map from the given iter l of bindings k_i -> v_i, added in order using add. If a key occurs several times, all its bindings are combined using the function f, with f key v1 v2 being called with v1 occurring later in the iter than v2.
to_iter m iterates on the whole map m, creating an iter of bindings. Like to_list.
of_list l builds a map from the given list l of bindings k_i -> v_i, added in order using add. If a key occurs several times, only its last binding will be present in the result.
of_list_with ~f l builds a map from the given list l of bindings k_i -> v_i, added in order using add. If a key occurs several times, all its bindings are combined using the function f, with f key v1 v2 being called with v1 occurring later in the list than v2.
add_list m l adds the given list l of bindings to the map m.
add_list ~f m l adds the given list l of bindings to the map m, using f to combine values that have the same key. If a key occurs several times, all its bindings are combined using the function f, with f key v1 v2 being called with v1 occurring later in the seq than v2.
to_list m builds a list of the bindings of the given map m. The order is unspecified.
CCMapExtensions of Standard Map
Provide useful functions and iterators on Map.S
module type S = sig ... endCCMap.Sget k m returns Some v if the current binding of k in m is v, or None if the key k is not present. Safe version of find.
get_or k m ~default returns the value associated to k if present, and returns default otherwise (if k doesn't belong in m).
update k f m calls f (Some v) if find k m = v, otherwise it calls f None. In any case, if the result is None k is removed from m, and if the result is Some v' then add k v' m is returned.
choose_opt m returns one binding of the given map m, or None if m is empty. Safe version of choose.
min_binding_opt m returns the smallest binding of the given map m, or None if m is empty. Safe version of min_binding.
max_binding_opt m returns the largest binding of the given map m, or None if m is empty. Safe version of max_binding.
find_opt k m returns Some v if the current binding of k in m is v, or None if the key k is not present. Safe version of find.
find_first f m where f is a monotonically increasing function, returns the binding of m with the lowest key k such that f k, or raises Not_found if no such key exists. See Map.S.find_first.
find_first_opt f m where f is a monotonically increasing function, returns an option containing the binding of m with the lowest key k such that f k, or None if no such key exists. Safe version of find_first.
val merge_safe :
+ f:( key -> [ `Left of 'a | `Right of 'b | `Both of 'a * 'b ] -> 'c option ) ->
+ 'a t ->
+ 'b t ->
+ 'c tmerge_safe ~f a b merges the maps a and b together.
add_seq m seq adds the given Seq.t of bindings to the map m. Like add_list. Renamed from add_std_seq since 3.0.
add_seq ~f m l adds the given seq l of bindings to the map m, using f to combine values that have the same key. If a key occurs several times, all its bindings are combined using the function f, with f key v1 v2 being called with v1 occurring later in the seq than v2.
of_seq seq builds a map from the given Seq.t of bindings. Like of_list. Renamed from of_std_seq since 3.0.
of_seq_with ~f l builds a map from the given seq l of bindings k_i -> v_i, added in order using add. If a key occurs several times, all its bindings are combined using the function f, with f key v1 v2 being called with v1 occurring later in the seq than v2.
add_iter m iter adds the given iter of bindings to the map m. Like add_list.
add_iter ~f m l adds the given iter l of bindings to the map m, using f to combine values that have the same key. If a key occurs several times, all its bindings are combined using the function f, with f key v1 v2 being called with v1 occurring later in the seq than v2.
of_iter iter builds a map from the given iter of bindings. Like of_list.
of_iter_with ~f l builds a map from the given iter l of bindings k_i -> v_i, added in order using add. If a key occurs several times, all its bindings are combined using the function f, with f key v1 v2 being called with v1 occurring later in the iter than v2.
to_iter m iterates on the whole map m, creating an iter of bindings. Like to_list.
of_list l builds a map from the given list l of bindings k_i -> v_i, added in order using add. If a key occurs several times, only its last binding will be present in the result.
of_list_with ~f l builds a map from the given list l of bindings k_i -> v_i, added in order using add. If a key occurs several times, all its bindings are combined using the function f, with f key v1 v2 being called with v1 occurring later in the list than v2.
add_list m l adds the given list l of bindings to the map m.
add_list ~f m l adds the given list l of bindings to the map m, using f to combine values that have the same key. If a key occurs several times, all its bindings are combined using the function f, with f key v1 v2 being called with v1 occurring later in the seq than v2.
to_list m builds a list of the bindings of the given map m. The order is unspecified.
CCMonomorphicCCNativeint.Infixx / y is the integer quotient of x and y. Integer division. Raise Division_by_zero if the second argument y is zero. This division rounds the real quotient of its arguments towards zero, as specified for Stdlib.(/).
x mod y is the integer remainder of x / y. If y <> zero, the result of x mod y satisfies the following properties: zero <= x mod y < abs y and x = ((x / y) * y) + (x mod y). If y = 0, x mod y raises Division_by_zero.
x lsl y shifts x to the left by y bits. The result is unspecified if y < 0 or y >= bitsize, where bitsize is 32 on a 32-bit platform and 64 on a 64-bit platform.
x lsr y shifts x to the right by y bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of x. The result is unspecified if y < 0 or y >= bitsize.
x asr y shifts x to the right by y bits. This is an arithmetic shift: the sign bit of x is replicated and inserted in the vacated bits. The result is unspecified if y < 0 or y >= bitsize.
CCNativeintHelpers for processor-native integers
This module provides operations on the type nativeint of signed 32-bit integers (on 32-bit platforms) or signed 64-bit integers (on 64-bit platforms). This integer type has exactly the same width as that of a pointer type in the C compiler. All arithmetic operations over nativeint are taken modulo 232 or 264 depending on the word size of the architecture.
Performance notice: values of type nativeint occupy more memory space than values of type int, and arithmetic operations on nativeint are generally slower than those on int. Use nativeint only when the application requires the extra bit of precision over the int type.
include module type of struct include Stdlib.Nativeint endval hash : t -> inthash x computes the hash of x. Like Stdlib.abs(to_intx).
val sign : t -> intsign x return 0 if x = 0, -1 if x < 0 and 1 if x > 0. Same as compare x zero.
pow base exponent returns base raised to the power of exponent. pow x y = x^y for positive integers x and y. Raises Invalid_argument if x = y = 0 or y < 0.
floor_div x n is integer division rounding towards negative infinity. It satisfies x = m * floor_div x n + rem x n.
range_by ~step i j iterates on integers from i to j included, where the difference between successive elements is step. Use a negative step for a decreasing list.
range i j iterates on integers from i to j included . It works both for decreasing and increasing ranges.
range' i j is like range but the second bound j is excluded. For instance range' 0 5 = Iter.of_list [0;1;2;3;4].
val random : t -> t random_genval random_small : t random_genval random_range : t -> t -> t random_genval of_string : string -> t optionof_string s is the safe version of of_string_exn. Like of_string_exn, but return None instead of raising.
val of_string_exn : string -> tof_string_exn s converts the given string s into a native integer. Alias to Nativeint.of_string. Convert the given string to a native integer. The string is read in decimal (by default, or if the string begins with 0u) or in hexadecimal, octal or binary if the string begins with 0x, 0o or 0b respectively.
The 0u prefix reads the input as an unsigned integer in the range [0, 2*CCNativeint.max_int+1]. If the input exceeds CCNativeint.max_int it is converted to the signed integer CCInt64.min_int + input - CCNativeint.max_int - 1.
Raise Failure "Nativeint.of_string" if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type nativeint.
val to_string_binary : t -> stringto_string_binary x returns the string representation of the integer x, in binary.
module Infix : sig ... endinclude module type of Infixx / y is the integer quotient of x and y. Integer division. Raise Division_by_zero if the second argument y is zero. This division rounds the real quotient of its arguments towards zero, as specified for Stdlib.(/).
x mod y is the integer remainder of x / y. If y <> zero, the result of x mod y satisfies the following properties: zero <= x mod y < abs y and x = ((x / y) * y) + (x mod y). If y = 0, x mod y raises Division_by_zero.
x lsl y shifts x to the left by y bits. The result is unspecified if y < 0 or y >= bitsize, where bitsize is 32 on a 32-bit platform and 64 on a 64-bit platform.
x lsr y shifts x to the right by y bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of x. The result is unspecified if y < 0 or y >= bitsize.
x asr y shifts x to the right by y bits. This is an arithmetic shift: the sign bit of x is replicated and inserted in the vacated bits. The result is unspecified if y < 0 or y >= bitsize.
CCOpt.Infixf <*> o returns Some (f x) if o is Some x and None if o is None.
CCOptPrevious Option module
include module type of CCOptionmap f o applies the function f to the element inside o, if any.
val map_or : default:'b -> ( 'a -> 'b ) -> 'a t -> 'bmap_or ~default f o is f x if o = Some x, default otherwise.
val map_lazy : ( unit -> 'b ) -> ( 'a -> 'b ) -> 'a t -> 'bmap_lazy default_fn f o is f x if o = Some x, default_fn () otherwise.
val is_some : _ t -> boolis_some (Some x) returns true otherwise it returns false.
val is_none : _ t -> boolis_none None returns true otherwise it returns false.
compare comp o1 o2 compares two options o1 and o2, using custom comparators comp for the value. None is always assumed to be less than Some _.
equal p o1 o2 tests for equality between option types o1 and o2, using a custom equality predicate p.
val return : 'a -> 'a treturn x is a monadic return, that is return x = Some x.
val none : 'a tAlias to None.
bind o f is f v if o is Some v, None otherwise. Monadic bind.
map2 f o1 o2 maps 'a option and 'b option to a 'c option using f.
val iter : ( 'a -> unit ) -> 'a t -> unititer f o applies f to o. Iterate on 0 or 1 element.
val fold : ( 'a -> 'b -> 'a ) -> 'a -> 'b t -> 'afold f init o is f init x if o is Some x, or init if o is None. Fold on 0 or 1 element.
filter f o returns Some x if o is Some x and f x is true, or None if f x is false or if o is None. Filter on 0 or 1 element.
val exists : ( 'a -> bool ) -> 'a t -> boolexists f o returns true iff there exists an element for which the provided function f evaluates to true.
val for_all : ( 'a -> bool ) -> 'a t -> boolfor_all f o returns true iff the provided function f evaluates to true for all elements.
val get_or : default:'a -> 'a t -> 'aget_or ~default o extracts the value from o, or returns default if o is None.
val value : 'a t -> default:'a -> 'avalue o ~default is similar to the Stdlib's Option.value and to get_or.
val get_exn : 'a t -> 'aget_exn o returns x if o is Some x or fails if o is None.
val get_exn_or : string -> 'a t -> 'aget_exn_or msg o returns x if o is Some x or fails with Invalid_argument msg if o is None.
val get_lazy : ( unit -> 'a ) -> 'a t -> 'aget_lazy default_fn o unwraps o, but if o is None it returns default_fn () instead.
sequence_l [x1; x2; …; xn] returns Some [y1; y2; …; yn] if every xi is Some yi. Otherwise, if the list contains at least one None, the result is None.
wrap ?handler f x calls f x and returns Some y if f x = y. If f x raises any exception, the result is None. This can be useful to wrap functions such as Map.S.find.
wrap2 ?handler f x y is similar to wrap but for binary functions.
or_lazy ~else_ o is o if o is Some _, else_ () if o is None.
val return_if : bool -> 'a -> 'a treturn_if b x applies Some or None depending on the boolean b. More precisely, return_if false x is None, and return_if true x is Some x.
module Infix : sig ... endinclude module type of Infixf <*> o returns Some (f x) if o is Some x and None if o is None.
val to_list : 'a t -> 'a listto_list o returns [x] if o is Some x or the empty list [] if o is None.
val of_list : 'a list -> 'a tof_list l returns Some x (x being the head of the list l), or None if l is the empty list.
val to_result : 'e -> 'a t -> ( 'a, 'e ) Stdlib.resultto_result e o returns Ok x if o is Some x, or Error e if o is None.
val to_result_lazy : ( unit -> 'e ) -> 'a t -> ( 'a, 'e ) Stdlib.resultto_result_lazy f o returns Ok x if o is Some x or Error f if o is None.
val of_result : ( 'a, _ ) Stdlib.result -> 'a tof_result result returns an option from a result.
val random : 'a random_gen -> 'a t random_genchoice_iter iter is similar to choice, but works on iter. It returns the first Some x occurring in iter, or None otherwise.
choice_seq seq works on Seq.t. It returns the first Some x occurring in seq, or None otherwise.
to_gen o is o as a gen. Some x is the singleton gen containing x and None is the empty gen.
val to_seq : 'a t -> 'a Stdlib.Seq.tto_seq o is o as a sequence Seq.t. Some x is the singleton sequence containing x and None is the empty sequence. Same as Stdlib.Option.to_seq Renamed from to_std_seq since 3.0.
CCOption.Infixf <*> o returns Some (f x) if o is Some x and None if o is None.
CCOptionBasic operations on the option type.
This module replaces `CCOpt`.
map f o applies the function f to the element inside o, if any.
val map_or : default:'b -> ( 'a -> 'b ) -> 'a t -> 'bmap_or ~default f o is f x if o = Some x, default otherwise.
val map_lazy : ( unit -> 'b ) -> ( 'a -> 'b ) -> 'a t -> 'bmap_lazy default_fn f o is f x if o = Some x, default_fn () otherwise.
val is_some : _ t -> boolis_some (Some x) returns true otherwise it returns false.
val is_none : _ t -> boolis_none None returns true otherwise it returns false.
compare comp o1 o2 compares two options o1 and o2, using custom comparators comp for the value. None is always assumed to be less than Some _.
equal p o1 o2 tests for equality between option types o1 and o2, using a custom equality predicate p.
val return : 'a -> 'a treturn x is a monadic return, that is return x = Some x.
val none : 'a tAlias to None.
bind o f is f v if o is Some v, None otherwise. Monadic bind.
map2 f o1 o2 maps 'a option and 'b option to a 'c option using f.
val iter : ( 'a -> unit ) -> 'a t -> unititer f o applies f to o. Iterate on 0 or 1 element.
val fold : ( 'a -> 'b -> 'a ) -> 'a -> 'b t -> 'afold f init o is f init x if o is Some x, or init if o is None. Fold on 0 or 1 element.
filter f o returns Some x if o is Some x and f x is true, or None if f x is false or if o is None. Filter on 0 or 1 element.
val exists : ( 'a -> bool ) -> 'a t -> boolexists f o returns true iff there exists an element for which the provided function f evaluates to true.
val for_all : ( 'a -> bool ) -> 'a t -> boolfor_all f o returns true iff the provided function f evaluates to true for all elements.
val get_or : default:'a -> 'a t -> 'aget_or ~default o extracts the value from o, or returns default if o is None.
val value : 'a t -> default:'a -> 'avalue o ~default is similar to the Stdlib's Option.value and to get_or.
val get_exn : 'a t -> 'aget_exn o returns x if o is Some x or fails if o is None.
val get_exn_or : string -> 'a t -> 'aget_exn_or msg o returns x if o is Some x or fails with Invalid_argument msg if o is None.
val get_lazy : ( unit -> 'a ) -> 'a t -> 'aget_lazy default_fn o unwraps o, but if o is None it returns default_fn () instead.
sequence_l [x1; x2; …; xn] returns Some [y1; y2; …; yn] if every xi is Some yi. Otherwise, if the list contains at least one None, the result is None.
wrap ?handler f x calls f x and returns Some y if f x = y. If f x raises any exception, the result is None. This can be useful to wrap functions such as Map.S.find.
wrap2 ?handler f x y is similar to wrap but for binary functions.
or_lazy ~else_ o is o if o is Some _, else_ () if o is None.
val return_if : bool -> 'a -> 'a treturn_if b x applies Some or None depending on the boolean b. More precisely, return_if false x is None, and return_if true x is Some x.
module Infix : sig ... endinclude module type of Infixf <*> o returns Some (f x) if o is Some x and None if o is None.
val to_list : 'a t -> 'a listto_list o returns [x] if o is Some x or the empty list [] if o is None.
val of_list : 'a list -> 'a tof_list l returns Some x (x being the head of the list l), or None if l is the empty list.
val to_result : 'e -> 'a t -> ( 'a, 'e ) Stdlib.resultto_result e o returns Ok x if o is Some x, or Error e if o is None.
val to_result_lazy : ( unit -> 'e ) -> 'a t -> ( 'a, 'e ) Stdlib.resultto_result_lazy f o returns Ok x if o is Some x or Error f if o is None.
val of_result : ( 'a, _ ) Stdlib.result -> 'a tof_result result returns an option from a result.
val random : 'a random_gen -> 'a t random_genchoice_iter iter is similar to choice, but works on iter. It returns the first Some x occurring in iter, or None otherwise.
choice_seq seq works on Seq.t. It returns the first Some x occurring in seq, or None otherwise.
to_gen o is o as a gen. Some x is the singleton gen containing x and None is the empty gen.
val to_seq : 'a t -> 'a Stdlib.Seq.tto_seq o is o as a sequence Seq.t. Some x is the singleton sequence containing x and None is the empty sequence. Same as Stdlib.Option.to_seq Renamed from to_std_seq since 3.0.
CCOrd.Infixval (<?>) : int -> ('a t * 'a * 'a) -> intc1 <?> (ord, x, y) returns the same as c1 if c1 is not 0; otherwise it uses ord to compare the two values x and y, of type 'a.
CCOrdOrder combinators
val poly : 'a tPolymorphic "magic" comparison. Use with care, as it will fail on some types.
val compare : 'a tPolymorphic "magic" comparison.
Opposite order. For example, opp cmp a b < 0 iff cmp b a > 0. This can be used to sort values in the opposite order, among other things.
val int : int tval string : string tval bool : bool tval float : float tval (<?>) : int -> ('a t * 'a * 'a) -> intc1 <?> (ord, x, y) returns the same as c1 if c1 is not 0; otherwise it uses ord to compare the two values x and y, of type 'a.
Example:
CCInt.compare 1 3
+<?> (String.compare, "a", "b")
+<?> (CCBool.compare, true, false)Same example, using only CCOrd::
CCOrd.(int 1 3
+ <?> (string, "a", "b")
+ <?> (bool, true, false))map f ord is the comparison function that, given objects x and y, projects x and y using f (e.g. using a record field) and then compares those projections with ord. Example: map fst CCInt.compare compares values of type (int * 'a) by their first component.
module Infix : sig ... endCCPairTuple Functions
val make : 'a -> 'b -> ( 'a, 'b ) tMake a tuple from its components.
map_fst f (x, y) returns (f x, y). Renamed from map1 since 3.0.
map_snd f (x, y) returns (x, f y). Renamed from map2 since 3.0.
Synonym to (***). Map on both sides of a tuple.
Like map but specialized for pairs with elements of the same type.
val map2 :
+ ( 'a1 -> 'b1 -> 'c1 ) ->
+ ( 'a2 -> 'b2 -> 'c2 ) ->
+ ('a1 * 'a2) ->
+ ('b1 * 'b2) ->
+ 'c1 * 'c2map2 f g (a,b) (x,y) return (f a x, g b y).
map_same2 f (a,b) (x,y) return (f a x, f b y).
Compose the given function with fst. Rename from map_fst since 3.0.
Compose the given function with snd. Rename from map_snd since 3.0.
f &&& g is fun x -> f x, g x. It splits the computations into two parts.
Synonym to merge.
dup_map f x = (x, f x). Duplicates the value and applies the function to the second copy.
CCParse.Debug_Debugging utils. EXPERIMENTAL
trace_fail name p behaves like p, but prints the error message of p on stderr whenever p fails.
trace_success name ~print p behaves like p, but prints successful runs of p using print.
CCParse.Errorval line_and_column : t -> int * intLine and column numbers of the error position.
val msg : t -> stringval to_string : t -> stringPrints the error
val pp : Stdlib.Format.formatter -> t -> unitPretty prints the error
CCParse.InfixAlias to map. p >|= f parses an item x using p, and returns f x.
Alias to bind. p >>= f results in a new parser which behaves as p then, in case of success, applies f to the result.
a <* b parses a into x, parses b and ignores its result, and returns x.
a *> b parses a, then parses b into x, and returns x. The result of a is ignored.
Alias to or_.
a <|> b tries to parse a, and if a fails without consuming any input, backtracks and tries to parse b, otherwise it fails as a.
a <?> msg behaves like a, but if a fails, a <?> msg fails with msg instead. Useful as the last choice in a series of <|>. For example: a <|> b <|> c <?> "expected one of a, b, c".
Alias to both. a ||| b parses a, then b, then returns the pair of their results.
CCParse.Positiontype t = positionval line : t -> intLine number, 0 based
val column : t -> intColumn number, 0 based
val line_and_column : t -> int * intLine and column number
val pp : Stdlib.Format.formatter -> t -> unitUnspecified pretty-printed version of the position.
CCParse.SliceFunctions on slices.
type t = sliceval is_empty : t -> boolIs the slice empty?
val length : t -> intLength of the slice
val to_string : t -> stringConvert the slice into a string. Linear time and memory in length slice
CCParse.UThis is useful to parse OCaml-like values in a simple way. All the parsers are whitespace-insensitive (they skip whitespace).
list p parses a list of p, with the OCaml conventions for start token "[", stop token "]" and separator ";". Whitespace between items are skipped.
val int : int tParse an int in decimal representation.
in_parens_opt p parses p in an arbitrary number of nested parenthesis (possibly 0).
option p parses "Some <x>" into Some x if p parses "<x>" into x, and parses "None" into None.
val hexa_int : int tParse an int int hexadecimal format. Accepts an optional 0x prefix, and ignores capitalization.
val word : string tNon empty string of alpha num, start with alpha.
val bool : bool tAccepts "true" or "false"
Parse a pair using OCaml syntactic conventions. The default is "(a, b)".
CCParseVery Simple Parser Combinators
These combinators can be used to write very simple parsers, for example to extract data from a line-oriented file, or as a replacement to Scanf.
Some more advanced example(s) can be found in the /examples directory.
open CCParse;;
+
+type tree = L of int | N of tree * tree;;
+
+let mk_leaf x = L x
+let mk_node x y = N(x,y)
+
+let ptree = fix @@ fun self ->
+ skip_space *>
+ ( (char '(' *> (pure mk_node <*> self <*> self) <* char ')')
+ <|>
+ (U.int >|= mk_leaf) )
+;;
+
+parse_string_exn ptree "(1 (2 3))" ;;
+parse_string_exn ptree "((1 2) (3 (4 5)))" ;;open Containers.Parse;;
+let p = U.list ~sep:"," U.word;;
+parse_string_exn p "[abc , de, hello ,world ]";;This makes a list of 100_000 integers, prints it and parses it back.
let p = CCParse.(U.list ~sep:"," U.int);;
+
+let l = CCList.(1 -- 100_000);;
+let l_printed =
+ CCFormat.(to_string (within "[" "]" (list ~sep:(return ",@,") int))) l;;
+
+let l' = CCParse.parse_string_exn p l_printed;;
+
+assert (l=l');;Some functions are marked "experimental" and are still subject to change.
module Position : sig ... endmodule Error : sig ... endtype +'a or_error = ( 'a, Error.t ) Stdlib.result'a or_error is either Ok x for some result x : 'a, or an error Error.t.
See stringify_result and Error.to_string to print the error message.
exception ParseError of Error.tval return : 'a -> 'a tAlways succeeds, without consuming its input.
bind f p results in a new parser which behaves as p then, in case of success, applies f to the result.
val eoi : unit tExpect the end of input, fails otherwise.
val empty : unit tSucceed with ().
val fail : string -> 'a tfail msg fails with the given message. It can trigger a backtrack.
parsing s p behaves the same as p, with the information that we are parsing s, if p fails. The message s is added to the error, it does not replace it, not does the location change (the error still points to the same location as in p).
set_error_message msg p behaves like p, but if p fails, set_error_message msg p fails with msg instead and at the current position. The internal error message of p is just discarded.
with_pos p behaves like p, but returns the (starting) position along with p's result.
EXPERIMENTAL
val any_char : char tany_char parses any character. It still fails if the end of input was reached.
val any_char_n : int -> string tany_char_n len parses exactly len characters from the input. Fails if the input doesn't contain at least len chars.
val char : char -> char tchar c parses the character c and nothing else.
A slice of the input, as returned by some combinators such as split_1 or split_list or take.
The idea is that one can use some parsers to cut the input into slices, e.g. split into lines, or split a line into fields (think CSV or TSV). Then a variety of parsers can be used on each slice to extract data from it using recurse.
Slices contain enough information to make it possible for recurse slice p to report failures (if p fails) using locations from the original input, not relative to the slice. Therefore, even after splitting the input into lines using, say, each_line, a failure to parse the 500th line will be reported at line 500 and not at line 1.
EXPERIMENTAL
module Slice : sig ... endFunctions on slices.
recurse slice p parses the slice (most likely obtained via another combinator, such as split_1 or split_n), using p.
The slice contains a position which is used to relocate error messages to their position in the whole input, not just relative to the slice.
EXPERIMENTAL
set_current_slice slice replaces the parser's state with slice.
EXPERIMENTAL
val chars_fold :
+ f:
+ ( 'acc ->
+ char ->
+ [ `Continue of 'acc
+ | `Consume_and_stop of 'acc
+ | `Stop of 'acc
+ | `Fail of string ] ) ->
+ 'acc ->
+ ('acc * slice) tchars_fold f acc0 folds over characters of the input. Each char c is passed, along with the current accumulator, to f; f can either:
`Stop acc. In this case the final accumulator acc is returned, and c is not consumed.`Consume_and_stop acc.`Fail msg. In this case the parser fails with the given message.`Continue acc. The parser continues to the next char with the new accumulator.This is a generalization of of chars_if that allows one to transform characters on the fly, skip some, handle escape sequences, etc. It can also be useful as a base component for a lexer.
val chars_fold_transduce :
+ f:
+ ( 'acc ->
+ char ->
+ [ `Continue of 'acc
+ | `Yield of 'acc * char
+ | `Consume_and_stop
+ | `Stop
+ | `Fail of string ] ) ->
+ 'acc ->
+ ('acc * string) tSame as char_fold but with the following differences:
`Continue _. The string is built from characters returned by `Yield.`Yield (acc, c) adds c to the returned string and continues parsing with acc.take len parses exactly len characters from the input. Fails if the input doesn't contain at least len chars.
take_if f takes characters as long as they satisfy the predicate f.
take1_if f takes characters as long as they satisfy the predicate f. Fails if no character satisfies f.
val char_if : ?descr:string -> ( char -> bool ) -> char tchar_if f parses a character c if f c = true. Fails if the next char does not satisfy f.
val chars_if : ( char -> bool ) -> string tchars_if f parses a string of chars that satisfy f. Cannot fail.
val chars1_if : ?descr:string -> ( char -> bool ) -> string tLike chars_if, but accepts only non-empty strings. chars1_if p fails if the string accepted by chars_if p is empty. chars1_if p is equivalent to take1_if p >|= Slice.to_string.
val endline : char tParse '\n'.
val space : char tTab or space.
val white : char tTab or space or newline.
val skip_chars : ( char -> bool ) -> unit tSkip 0 or more chars satisfying the predicate.
val skip_space : unit tSkip ' ' and '\t'.
val skip_white : unit tSkip ' ' and '\t' and '\n'.
suspend f is the same as f (), but evaluates f () only when needed.
A practical use case is to implement recursive parsers manually, as described in fix. The parser is let rec p () = …, and suspend p can be used in the definition to use p.
val string : string -> string tstring s parses exactly the string s, and nothing else.
many p parses p repeatedly, until p fails, and collects the results into a list.
optional p tries to parse p, and return () whether it succeeded or failed. Cannot fail itself. It consumes input if p succeeded (as much as p consumed), but consumes not input if p failed.
try_ p is just like p (it used to play a role in backtracking semantics but no more).
try_opt p tries to parse using p, and return Some x if p succeeded with x (and consumes what p consumed). Otherwise it returns None and consumes nothing. This cannot fail.
many_until ~until p parses as many p as it can until the until parser successfully returns. If p fails before that then many_until ~until p fails as well. Typically until can be a closing ')' or another termination condition, and what is consumed by until is also consumed by many_until ~until p.
EXPERIMENTAL
try_or p1 ~f ~else_:p2 attempts to parse x using p1, and then becomes f x. If p1 fails, then it becomes p2. This can be useful if f is expensive but only ever works if p1 matches (e.g. after an opening parenthesis or some sort of prefix).
try_or_l ?else_ l tries each pair (test, p) in order. If the n-th test succeeds, then try_or_l l behaves like n-th p, whether p fails or not. If test consumes input, the state is restored before calling p. If they all fail, and else_ is defined, then it behaves like else_. If all fail, and else_ is None, then it fails as well.
This is a performance optimization compared to (<|>). We commit to a branch if the test succeeds, without backtracking at all. It can also provide better error messages, because failures in the parser will not be reported as failures in try_or_l.
See lookahead_ignore for a convenient way of writing the test conditions.
or_ p1 p2 tries to parse p1, and if it fails, tries p2 from the same position.
both a b parses a, then b, then returns the pair of their results.
many1 p is like many p excepts it fails if the list is empty (i.e. it needs p to succeed at least once).
skip p parses zero or more times p and ignores its result. It is eager, meaning it will continue as long as p succeeds. As soon as p fails, skip p stops consuming any input.
Same as sep but stop when until parses successfully.
lookahead p behaves like p, except it doesn't consume any input.
EXPERIMENTAL
lookahead_ignore p tries to parse input with p, and succeeds if p succeeds. However it doesn't consume any input and returns (), so in effect its only use-case is to detect whether p succeeds, e.g. in try_or_l.
EXPERIMENTAL
Fixpoint combinator. fix (fun self -> p) is the parser p, in which self refers to the parser p itself (which is useful to parse recursive structures.
An alternative, manual implementation to let p = fix (fun self -> q) is:
let rec p () =
+ let self = suspend p in
+ qval line_str : string tline_str is line >|= Slice.to_string. It parses the next line and turns the slice into a string. The state points to the character immediately after the '\n' character.
split_1 ~on_char looks for on_char in the input, and returns a pair sl1, sl2, where:
sl1 is the slice of the input the precedes the first occurrence of on_char, or the whole input if on_char cannot be found. It does not contain on_char.sl2 is the slice that comes after on_char, or None if on_char couldn't be found. It doesn't contain the first occurrence of on_char (if any).The parser is now positioned at the end of the input.
EXPERIMENTAL
split_list ~on_char splits the input on all occurrences of on_char, returning a list of slices.
EXPERIMENTAL
split_list_at_most ~on_char n applies split_1 ~on_char at most n times, to get a list of n+1 elements. The last element might contain on_char. This is useful to limit the amount of work done by split_list.
EXPERIMENTAL
split_2 ~on_char splits the input into exactly 2 fields, and fails if the split yields less or more than 2 items. EXPERIMENTAL
split_list_map ~on_char p uses split_list ~on_char to split the input, then parses each chunk of the input thus obtained using p.
The difference with sep ~by:(char on_char) p is that sep calls p first, and only tries to find on_char after p returns. While it is more flexible, this technique also means p has to be careful not to consume on_char by error.
A useful specialization of this is each_line, which is basically each_split ~on_char:'\n' p.
EXPERIMENTAL
all returns all the unconsumed input as a slice, and consumes it. Use Slice.to_string to turn it into a string.
Note that lookahead all can be used to peek at the rest of the input without consuming anything.
val all_str : string tall_str accepts all the remaining chars and extracts them into a string. Similar to all but with a string.
EXPERIMENTAL
Memoize the parser. memo p will behave like p, but when called in a state (read: position in input) it has already processed, memo p returns a result directly. The implementation uses an underlying hashtable. This can be costly in memory, but improve the run time a lot if there is a lot of backtracking involving p.
Do not call memo inside other functions, especially with (>>=), map, etc. being so prevalent. Instead the correct way to use it is in a toplevel definition:
let my_expensive_parser = memo (foo *> bar >>= fun i -> …)This function is not thread-safe.
module Infix : sig ... endinclude module type of InfixAlias to map. p >|= f parses an item x using p, and returns f x.
Alias to bind. p >>= f results in a new parser which behaves as p then, in case of success, applies f to the result.
a <* b parses a into x, parses b and ignores its result, and returns x.
a *> b parses a, then parses b into x, and returns x. The result of a is ignored.
Alias to or_.
a <|> b tries to parse a, and if a fails without consuming any input, backtracks and tries to parse b, otherwise it fails as a.
a <?> msg behaves like a, but if a fails, a <?> msg fails with msg instead. Useful as the last choice in a series of <|>. For example: a <|> b <|> c <?> "expected one of a, b, c".
Alias to both. a ||| b parses a, then b, then returns the pair of their results.
val stringify_result : 'a or_error -> ( 'a, string ) Stdlib.resultTurn a Error.t-oriented result into a more basic string result.
val parse_string : 'a t -> string -> ( 'a, string ) Stdlib.resultParse a string using the parser.
Version of parse_string that returns a more detailed error.
val parse_string_exn : 'a t -> string -> 'aval parse_file : 'a t -> string -> ( 'a, string ) Stdlib.resultparse_file p filename parses file named filename with p by opening the file and reading it whole.
Version of parse_file that returns a more detailed error.
val parse_file_exn : 'a t -> string -> 'aSame as parse_file, but
module U : sig ... endmodule Debug_ : sig ... endDebugging utils. EXPERIMENTAL
CCRandomRandom Generators
include module type of struct include Stdlib.Random endtype 'a t = state -> 'aRandom generator for values of type 'a.
type 'a random_gen = 'a tval return : 'a -> 'a treturn x is the generator that always returns x. Example: let random_int = return 4 (* fair dice roll *).
Delay evaluation. Useful for side-effectful generators that need some code to run for every call. Example:
let gensym = let r = ref 0 in fun () -> incr r; !r ;;
+
+delay (fun () ->
+ let name = gensym() in
+ small_int >>= fun i -> return (name,i)
+)val choose_return : 'a list -> 'a tChoose among the list.
replicate n g makes a list of n elements which are all generated randomly using g.
sample_without_replacement n g makes a list of n elements which are all generated randomly using g with the added constraint that none of the generated random values are equal.
val pick_list : 'a list -> 'a tPick an element at random from the list.
val pick_array : 'a array -> 'a tPick an element at random from the array.
val small_int : int tA small int (100).
val int : int -> int tRandom int within the given range.
val int_range : int -> int -> int tInclusive range.
val small_float : float tA reasonably small float (100.0).
val float : float -> float tRandom float within the given range.
val float_range : float -> float -> float tInclusive range. float_range a b assumes a < b.
val split : int -> (int * int) option tSplit a positive value n into n1,n2 where n = n1 + n2.
val split_list : int -> len:int -> int list option tSplit a value n into a list of values whose sum is n and whose length is length. The list is never empty and does not contain 0.
retry g calls g until it returns some value, or until the maximum number of retries was reached. If g fails, then it counts for one iteration, and the generator retries.
try_successively l tries each generator of l, one after the other. If some generator succeeds its result is returned, else the next generator is tried.
a <?> b is a choice operator. It first tries a, and returns its result if successful. If a fails, then b is returned.
val fix :
+ ?sub1:( 'a t -> 'a t ) list ->
+ ?sub2:( 'a t -> 'a t -> 'a t ) list ->
+ ?subn:(int t * ( 'a list t -> 'a t )) list ->
+ base:'a t ->
+ int t ->
+ 'a tRecursion combinators, for building recursive values. The integer generator is used to provide fuel. The sub_ generators should use their arguments only once!
val pure : 'a -> 'a tLet operators on OCaml >= 4.08.0, nothing otherwise
CCRefHelpers for references
val create : 'a -> 'a tAlias to ref.
val iter : ( 'a -> unit ) -> 'a t -> unitCall the function on the content of the reference.
val update : ( 'a -> 'a ) -> 'a t -> unitUpdate the reference's content with the given function.
val incr_then_get : int t -> intincr_then_get r increments r and returns its new value, think ++r.
val get_then_incr : int t -> intget_then_incr r increments r and returns its old value, think r++.
val protect : 'a t -> 'a -> ( unit -> 'b ) -> 'bprotect r x f sets r := x; calls f(); restores r to its old value; and returns the result of f().
val to_list : 'a t -> 'a listCCResult.InfixInfix version of map with reversed arguments.
Monadic composition. e >>= f proceeds as f x if e is Ok x or returns e if e is an Error.
a <*> b evaluates a and b, and, in case of success, returns Ok (a b). Otherwise, it fails, and the error of a is chosen over the error of b if both fail.
Traverse.1-Mval return : 'a -> 'a tMonadic return.
CCResult.TraverseCCResultError Monad
Uses the new "result" type from OCaml 4.03.
val return : 'a -> ( 'a, 'err ) tSuccessfully return a value.
val fail : 'err -> ( 'a, 'err ) tFail with an error.
val of_exn : exn -> ( 'a, string ) tof_exn e uses Printexc to print the exception as a string.
val of_exn_trace : exn -> ( 'a, string ) tof_exn_trace e is similar to of_exn e, but it adds the stacktrace to the error message.
Remember to call Printexc.record_backtrace true and compile with the debug flag for this to work.
val fail_printf :
+ ( 'a, Stdlib.Buffer.t, unit, ( 'b, string ) t ) Stdlib.format4 ->
+ 'afail_printf format uses format to obtain an error message and then returns Error msg.
val fail_fprintf :
+ ( 'a, Stdlib.Format.formatter, unit, ( 'b, string ) t ) Stdlib.format4 ->
+ 'afail_fprintf format uses format to obtain an error message and then returns Error msg.
add_ctx msg leaves Ok x untouched, but transforms Error s into Error s' where s' contains the additional context given by msg.
val add_ctxf :
+ ( 'a, Stdlib.Format.formatter, unit, ( 'b, string ) t -> ( 'b, string ) t )
+ Stdlib.format4 ->
+ 'aadd_ctxf format_message is similar to add_ctx but with Format for printing the message (eagerly). Example:
add_ctxf "message(number %d, foo: %B)" 42 true (Error "error)"Map a fallible operation through an option.
Like map, but also with a function that can transform the error message in case of failure.
val iter : ( 'a -> unit ) -> ( 'a, _ ) t -> unitApply the function only in case of Ok.
val iter_err : ( 'err -> unit ) -> ( _, 'err ) t -> unitApply the function in case of Error.
val get_exn : ( 'a, _ ) t -> 'aExtract the value x from Ok x, fails otherwise. You should be careful with this function, and favor other combinators whenever possible.
val get_or : ( 'a, _ ) t -> default:'a -> 'aget_or e ~default returns x if e = Ok x, default otherwise.
val get_or_failwith : ( 'a, string ) t -> 'aget_or_failwith e returns x if e = Ok x, fails otherwise.
val get_lazy : ( 'b -> 'a ) -> ( 'a, 'b ) t -> 'aget_lazy default_fn x unwraps x, but if x = Error e it returns default_fr e instead.
val map_or : ( 'a -> 'b ) -> ( 'a, 'c ) t -> default:'b -> 'bmap_or f e ~default returns f x if e = Ok x, default otherwise.
val catch : ( 'a, 'err ) t -> ok:( 'a -> 'b ) -> err:( 'err -> 'b ) -> 'bcatch e ~ok ~err calls either ok or err depending on the value of e.
val fold : ok:( 'a -> 'b ) -> error:( 'err -> 'b ) -> ( 'a, 'err ) t -> 'bfold ~ok ~error e opens e and, if e = Ok x, returns ok x, otherwise e = Error s and it returns error s.
val fold_ok : ( 'a -> 'b -> 'a ) -> 'a -> ( 'b, _ ) t -> 'afold_ok f acc r will compute f acc x if r=Ok x, and return acc otherwise, as if the result were a mere option.
val is_ok : ( 'a, 'err ) t -> boolReturn true if Ok.
val is_error : ( 'a, 'err ) t -> boolReturn true if Error.
val guard : ( unit -> 'a ) -> ( 'a, exn ) tguard f runs f () and returns its result wrapped in Ok. If f () raises some exception e, then it fails with Error e.
val guard_str : ( unit -> 'a ) -> ( 'a, string ) tval guard_str_trace : ( unit -> 'a ) -> ( 'a, string ) tLike guard_str but uses of_exn_trace instead of of_exn so that the stack trace is printed.
val wrap2 : ( 'a -> 'b -> 'c ) -> 'a -> 'b -> ( 'c, exn ) tLike guard but gives the function two arguments.
val wrap3 : ( 'a -> 'b -> 'c -> 'd ) -> 'a -> 'b -> 'c -> ( 'd, exn ) tLike guard but gives the function three arguments.
join t, in case of success, returns Ok o from Ok (Ok o). Otherwise, it fails with Error e where e is the unwrapped error of t.
both a b, in case of success, returns Ok (o, o') with the ok values of a and b. Otherwise, it fails, and the error of a is chosen over the error of b if both fail.
module Infix : sig ... endinclude module type of InfixInfix version of map with reversed arguments.
Monadic composition. e >>= f proceeds as f x if e is Ok x or returns e if e is an Error.
a <*> b evaluates a and b, and, in case of success, returns Ok (a b). Otherwise, it fails, and the error of a is chosen over the error of b if both fail.
Same as map_l id: returns Ok [x1;…;xn] if l=[Ok x1; …; Ok xn], or the first error otherwise.
map_l f [a1; …; an] applies the function f to a1, …, an ,and, in case of success for every element, returns the list of Ok-value. Otherwise, it fails and returns the first error encountered. Tail-recursive.
choose l selects a member of l that is a Ok _ value, or returns Error l otherwise, where l is the list of errors.
retry n f calls f at most n times, returning the first result of f () that doesn't fail. If f fails n times, retry n f fails with the list of successive errors.
module type MONAD = sig ... endval to_opt : ( 'a, _ ) t -> 'a optionConvert a result to an option.
val of_opt : 'a option -> ( 'a, string ) tof_opt opt converts Some v to Ok v and None to Error "of_opt".
val to_seq : ( 'a, _ ) t -> 'a Stdlib.Seq.tRenamed from to_std_seq since 3.0.
CCResult.MONADval return : 'a -> 'a tMonadic return.
CCSeq.InfixTraverse.1-MCCSeq.TraverseCCSeqHelpers for the standard Seq type
See oseq for a richer API.
val nil : 'a tval empty : 'a tval singleton : 'a -> 'a tval init : int -> ( int -> 'a ) -> 'a tinit n f corresponds to the sequence f 0; f 1; ...; f (n-1).
val repeat : ?n:int -> 'a -> 'a trepeat ~n x repeats x n times then stops. If n is omitted, then x is repeated forever.
val forever : ( unit -> 'a ) -> 'a tforever f corresponds to the infinit sequence containing all the f ().
val iterate : ( 'a -> 'a ) -> 'a -> 'a titerate f a corresponds to the infinit sequence containing a, f a, f (f a), ...]
val unfold : ( 'b -> ('a * 'b) option ) -> 'b -> 'a tunfold f acc calls f acc and:
f acc = Some (x, acc'), yield x, continue with unfold f acc'.f acc = None, stops.val is_empty : 'a t -> boolis_empty xs checks in the sequence xs is empty
val head : 'a t -> 'a optionHead of the list.
val fold : ( 'a -> 'b -> 'a ) -> 'a -> 'b t -> 'aFold on values.
val foldi : ( 'a -> int -> 'b -> 'a ) -> 'a -> 'b t -> 'afold_lefti f init xs applies f acc i x where acc is the result of the previous computation or init for the first one, i is the index in the sequence (starts at 0) and x is the element of the sequence.
val iter : ( 'a -> unit ) -> 'a t -> unitval iteri : ( int -> 'a -> unit ) -> 'a t -> unitIterate with index (starts at 0).
val length : _ t -> intNumber of elements in the list. Will not terminate if the list if infinite: use (for instance) take to make the list finite if necessary.
Fair product of two (possibly infinite) lists into a new list. Lazy. The first parameter is used to combine each pair of elements.
Alias of product_with.
Specialization of product_with producing tuples.
group eq l groups together consecutive elements that satisfy eq. Lazy. For instance group (=) [1;1;1;2;2;3;3;1] yields [1;1;1]; [2;2]; [3;3]; [1].
uniq eq l returns l but removes consecutive duplicates. Lazy. In other words, if several values that are equal follow one another, only the first of them is kept.
val for_all : ( 'a -> bool ) -> 'a t -> boolfor_all p [a1; ...; an] checks if all elements of the sequence satisfy the predicate p. That is, it returns (p a1) && ... && (p an) for a non-empty list and true if the sequence is empty. It consumes the sequence until it finds an element not satisfying the predicate.
val exists : ( 'a -> bool ) -> 'a t -> boolexists p [a1; ...; an] checks if at least one element of the sequence satisfies the predicate p. That is, it returns (p a1) || ... || (p an) for a non-empty sequence and false if the list is empty. It consumes the sequence until it finds an element satisfying the predicate.
val find : ( 'a -> bool ) -> 'a t -> 'a optionfind p [a1; ...; an] return Some ai for the first ai satisfying the predicate p and return None otherwise.
val find_map : ( 'a -> 'b option ) -> 'a t -> 'b optionfind f [a1; ...; an] return Some (f ai) for the first ai such that f ai = Some _ and return None otherwise.
scan f init xs is the sequence containing the intermediate result of fold f init xs.
val range : int -> int -> int tval (--) : int -> int -> int ta -- b is the range of integers containing a and b (therefore, never empty).
val (--^) : int -> int -> int ta -- b is the integer range from a to b, where b is excluded.
Fold on two collections at once. Stop at soon as one of them ends.
Map on two collections at once. Stop as soon as one of the arguments is exhausted.
Iterate on two collections at once. Stop as soon as one of them ends.
Combine elements pairwise. Stop as soon as one of the lists stops.
Eager sort. Require the iterator to be finite. O(n ln(n)) time and space.
Eager sort that removes duplicate values. Require the iterator to be finite. O(n ln(n)) time and space.
val return : 'a -> 'a tval pure : 'a -> 'a tInfix version of fair_flat_map.
module Infix : sig ... endmodule type MONAD = sig ... endval of_list : 'a list -> 'a tval to_list : 'a t -> 'a listGather all values into a list.
val of_array : 'a array -> 'a tIterate on the array.
val to_array : 'a t -> 'a arrayConvert into array.
val of_string : string -> char tIterate on characters.
val pp :
+ ?pp_start:unit printer ->
+ ?pp_stop:unit printer ->
+ ?pp_sep:unit printer ->
+ 'a printer ->
+ 'a t printerpp ~pp_start ~pp_stop ~pp_sep pp_item ppf s formats the sequence s on ppf. Each element is formatted with pp_item, pp_start is called at the beginning, pp_stop is called at the end, pp_sep is called between each elements. By defaults pp_start and pp_stop does nothing and pp_sep defaults to (fun out -> Format.fprintf out ",@ ").
CCSeq.MONADCCSet.MakeSafe version of find_first.
CCSetWrapper around Set
module type S = sig ... endCCSet.SSafe version of find_first.
CCSexp.Decoderval of_lexbuf : Stdlib.Lexing.lexbuf -> tval next : t -> sexp parse_resultParse the next S-expression or return an error if the input isn't long enough or isn't a proper S-expression.
val to_list : t -> sexp list CCSexp_intf.or_errorRead all the values from this decoder.
Make.Decoderval of_lexbuf : Stdlib.Lexing.lexbuf -> tval next : t -> sexp parse_resultParse the next S-expression or return an error if the input isn't long enough or isn't a proper S-expression.
val to_list : t -> sexp list CCSexp_intf.or_errorRead all the values from this decoder.
Make.1-Sexpval make_loc : ( (int * int) -> (int * int) -> string -> loc ) optionIf provided, builds a location from a pair of (line,column) positions, and a (possibly dummy) filename
CCSexp.MakeThis builds a parser and printer for S-expressions represented as in the Sexp argument.
include CCSexp_intf.S0 with type t = Sexp.ttype t = Sexp.ttype sexp = tval atom : string -> tMake an atom out of this string.
val of_int : int -> tval of_bool : bool -> tval of_float : float -> tval of_unit : tof_variant name args is used to encode algebraic variants into a S-expr. For instance of_variant "some" [of_int 1] represents the value Some 1.
val to_buf : Stdlib.Buffer.t -> t -> unitval to_string : t -> stringval to_file : string -> t -> unitval to_file_iter : string -> t CCSexp_intf.iter -> unitPrint the given iter of expressions to a file.
val to_chan : Stdlib.out_channel -> t -> unitval pp : Stdlib.Format.formatter -> t -> unitPretty-printer nice on human eyes (including indentation).
val pp_noindent : Stdlib.Format.formatter -> t -> unitRaw, direct printing as compact as possible.
val parse_string : string -> t CCSexp_intf.or_errorParse a string.
val parse_string_list : string -> t list CCSexp_intf.or_errorParse a string into a list of S-exprs.
val parse_chan : Stdlib.in_channel -> t CCSexp_intf.or_errorParse a S-expression from the given channel. Can read more data than necessary, so don't use this if you need finer-grained control (e.g. to read something else after the S-exp).
val parse_chan_gen :
+ Stdlib.in_channel ->
+ t CCSexp_intf.or_error CCSexp_intf.genParse a channel into a generator of S-expressions.
val parse_chan_list : Stdlib.in_channel -> t list CCSexp_intf.or_errorval parse_file : string -> t CCSexp_intf.or_errorOpen the file and read a S-exp from it.
val parse_file_list : string -> t list CCSexp_intf.or_errorOpen the file and read a S-exp from it.
type loc = Sexp.locLocations for the S-expressions.
A parser of 'a can return Yield x when it parsed a value, or Fail e when a parse error was encountered, or End if the input was empty.
module Decoder : sig ... endCCSexpHandling S-expressions
module type SEXP = CCSexp_intf.SEXPmodule type S = CCSexp_intf.SA simple, structural representation of S-expressions.
include S with type t := tinclude CCSexp_intf.S0 with type t := ttype sexp = tval of_int : int -> tval of_bool : bool -> tval of_float : float -> tval of_unit : tof_variant name args is used to encode algebraic variants into a S-expr. For instance of_variant "some" [of_int 1] represents the value Some 1.
val to_buf : Stdlib.Buffer.t -> t -> unitval to_string : t -> stringval to_file : string -> t -> unitval to_file_iter : string -> t CCSexp_intf.iter -> unitPrint the given iter of expressions to a file.
val to_chan : Stdlib.out_channel -> t -> unitval pp : Stdlib.Format.formatter -> t -> unitPretty-printer nice on human eyes (including indentation).
val pp_noindent : Stdlib.Format.formatter -> t -> unitRaw, direct printing as compact as possible.
val parse_string : string -> t CCSexp_intf.or_errorParse a string.
val parse_string_list : string -> t list CCSexp_intf.or_errorParse a string into a list of S-exprs.
val parse_chan : Stdlib.in_channel -> t CCSexp_intf.or_errorParse a S-expression from the given channel. Can read more data than necessary, so don't use this if you need finer-grained control (e.g. to read something else after the S-exp).
val parse_chan_gen :
+ Stdlib.in_channel ->
+ t CCSexp_intf.or_error CCSexp_intf.genParse a channel into a generator of S-expressions.
val parse_chan_list : Stdlib.in_channel -> t list CCSexp_intf.or_errorval parse_file : string -> t CCSexp_intf.or_errorOpen the file and read a S-exp from it.
val parse_file_list : string -> t list CCSexp_intf.or_errorOpen the file and read a S-exp from it.
A parser of 'a can return Yield x when it parsed a value, or Fail e when a parse error was encountered, or End if the input was empty.
module Decoder : sig ... endval atom : string -> tBuild an atom directly from a string.
CCSexp_intfmodule type BASIC_SEXP = sig ... endmodule type SEXP = sig ... endmodule type S0 = sig ... endmodule type S = sig ... endCCSexp_intf.BASIC_SEXPval atom : string -> tS.Decoderval of_lexbuf : Stdlib.Lexing.lexbuf -> tval next : t -> sexp parse_resultParse the next S-expression or return an error if the input isn't long enough or isn't a proper S-expression.
CCSexp_intf.Sinclude S0type sexp = tval atom : string -> tMake an atom out of this string.
val of_int : int -> tval of_bool : bool -> tval of_float : float -> tval of_unit : tof_variant name args is used to encode algebraic variants into a S-expr. For instance of_variant "some" [of_int 1] represents the value Some 1.
val to_buf : Stdlib.Buffer.t -> t -> unitval to_string : t -> stringval to_file : string -> t -> unitval to_chan : Stdlib.out_channel -> t -> unitval pp : Stdlib.Format.formatter -> t -> unitPretty-printer nice on human eyes (including indentation).
val pp_noindent : Stdlib.Format.formatter -> t -> unitRaw, direct printing as compact as possible.
Parse a S-expression from the given channel. Can read more data than necessary, so don't use this if you need finer-grained control (e.g. to read something else after the S-exp).
Parse a channel into a generator of S-expressions.
A parser of 'a can return Yield x when it parsed a value, or Fail e when a parse error was encountered, or End if the input was empty.
module Decoder : sig ... endCCSexp_intf.S0type sexp = tval atom : string -> tMake an atom out of this string.
val of_int : int -> tval of_bool : bool -> tval of_float : float -> tval of_unit : tof_variant name args is used to encode algebraic variants into a S-expr. For instance of_variant "some" [of_int 1] represents the value Some 1.
val to_buf : Stdlib.Buffer.t -> t -> unitval to_string : t -> stringval to_file : string -> t -> unitval to_chan : Stdlib.out_channel -> t -> unitval pp : Stdlib.Format.formatter -> t -> unitPretty-printer nice on human eyes (including indentation).
val pp_noindent : Stdlib.Format.formatter -> t -> unitRaw, direct printing as compact as possible.
Parse a S-expression from the given channel. Can read more data than necessary, so don't use this if you need finer-grained control (e.g. to read something else after the S-exp).
Parse a channel into a generator of S-expressions.
CCSexp_intf.SEXPval make_loc : ( (int * int) -> (int * int) -> string -> loc ) optionIf provided, builds a location from a pair of (line,column) positions, and a (possibly dummy) filename
CCSexp_lexval token : Stdlib.Lexing.lexbuf -> tokenval __ocaml_lex_token_rec : Stdlib.Lexing.lexbuf -> int -> tokenCCShims_CCShims_syntaxmodule type LET = sig ... endLet operators on OCaml >= 4.08.0, nothing otherwise
CCShims_syntax.LETLet operators on OCaml >= 4.08.0, nothing otherwise
CCString.Findval compile : string -> [ `Direct ] patternval rcompile : string -> [ `Reverse ] patternval find : ?start:int -> pattern:[ `Direct ] pattern -> string -> intfind ~start ~pattern s searches for pattern in the string s, left-to-right.
val rfind : ?start:int -> pattern:[ `Reverse ] pattern -> string -> intrfind ~start ~pattern s searches for pattern in the string s, right-to-left.
CCString.InfixCCString.SplitSpecification of what to do with empty blocks, as in split ~by:"-" "-a-b-".
{first=false; last=false} will return ""; "a"; "b"; ""{first=true; last=false} will return "a"; "b" ""{first=false; last=true} will return ""; "a"; "b"{first=true; last=true} will return "a"; "b"The default value of all remaining functions is Drop_none.
val no_drop : drop_if_emptyno_drop does not drop any group, even empty and on borders.
val list_ :
+ ?drop:drop_if_empty ->
+ by:string ->
+ string ->
+ (string * int * int) listlist_ ~drop ~by s splits the given string s along the given separator by. Should only be used with very small separators, otherwise use Containers_string.KMP.
val gen :
+ ?drop:drop_if_empty ->
+ by:string ->
+ string ->
+ (string * int * int) gengen ~drop ~by s splits the given string s along the given separator by. Returns a gen of slices.
val iter :
+ ?drop:drop_if_empty ->
+ by:string ->
+ string ->
+ (string * int * int) iteriter ~drop ~by s splits the given string s along the given separator by. Returns an iter of slices.
val seq :
+ ?drop:drop_if_empty ->
+ by:string ->
+ string ->
+ (string * int * int) Stdlib.Seq.tseq ~drop ~by s splits the given string s along the given separator by. Returns a Seq.t of slices. Renamed from std_seq since 3.0.
Those split functions actually copy the substrings, which can be more convenient but less efficient in general.
val list_cpy : ?drop:drop_if_empty -> by:string -> string -> string listlist_cpy ~drop ~by s splits the given string s along the given separator by. Returns a list of strings.
val gen_cpy : ?drop:drop_if_empty -> by:string -> string -> string gengen_cpy ~drop ~by s splits the given string s along the given separator by. Returns a gen of strings.
val iter_cpy : ?drop:drop_if_empty -> by:string -> string -> string iteriter_cpy ~drop ~by s splits the given string s along the given separator by. Returns an iter of strings.
val seq_cpy : ?drop:drop_if_empty -> by:string -> string -> string Stdlib.Seq.tseq_cpy ~drop ~by s splits the given string s along the given separator by. Returns a Seq.t of strings. Renamed from std_seq_cpy since 3.0.
left ~by s splits on the first occurrence of by from the leftmost part of the string s.
left_exn ~by s splits on the first occurrence of by from the leftmost part of the string s.
right ~by s splits on the first occurrence of by from the rightmost part of the string s.
CCStringBasic String Utils
include module type of struct include Stdlib.String endval to_seqi : t -> (int * char) Stdlib.Seq.tval get_utf_8_uchar : t -> int -> Stdlib.Uchar.utf_decodeval is_valid_utf_8 : t -> boolval get_utf_16be_uchar : t -> int -> Stdlib.Uchar.utf_decodeval is_valid_utf_16be : t -> boolval get_utf_16le_uchar : t -> int -> Stdlib.Uchar.utf_decodeval is_valid_utf_16le : t -> boolval length : t -> intlength s returns the length (number of characters) of the given string s.
val blit : t -> int -> Stdlib.Bytes.t -> int -> int -> unitblit src src_pos dst dst_pos len copies len characters from string src starting at character indice src_pos, to the Bytes sequence dst starting at character indice dst_pos. Like String.blit. Compatible with the -safe-string option.
val fold : ( 'a -> char -> 'a ) -> 'a -> t -> 'afold f init s folds on chars by increasing index. Computes f(… (f (f init s.[0]) s.[1]) …) s.[n-1].
val foldi : ( 'a -> int -> char -> 'a ) -> 'a -> t -> 'afoldi f init s is just like fold, but it also passes in the index of each chars as second argument to the folded function f.
val to_seq : t -> char Stdlib.Seq.tto_seq s returns the Seq.t of characters contained in the string s. Renamed from to std_seq since 3.0.
val to_list : t -> char listto_list s returns the list of characters contained in the string s.
val pp_buf : Stdlib.Buffer.t -> t -> unitpp_buf buf s prints s to the buffer buf. Renamed from pp since 2.0.
val pp : Stdlib.Format.formatter -> t -> unitpp f s prints the string s within quotes to the formatter f. Renamed from print since 2.0.
compare s1 s2 compares the strings s1 and s2 and returns an integer that indicates their relative position in the sort order.
pad ~side ~c n s ensures that the string s is at least n bytes long, and pads it on the side with c if it's not the case.
val of_gen : char gen -> stringof_gen gen converts a gen of characters to a string.
val of_iter : char iter -> stringof_iter iter converts an iter of characters to a string.
of_seq seq converts a seq of characters to a string. Renamed from of_std_seq since 3.0.
to_array s returns the array of characters contained in the string s.
find ~start ~sub s returns the starting index of the first occurrence of sub within s or -1.
val find_all : ?start:int -> sub:string -> string -> int genfind_all ~start ~sub s finds all occurrences of sub in s, even overlapping instances and returns them in a generator gen.
find_all_l ~sub s finds all occurrences of sub in s and returns them in a list.
mem ~start ~sub s is true iff sub is a substring of s.
rfind ~sub s finds sub in string s from the right, returns its first index or -1. Should only be used with very small sub.
val replace :
+ ?which:[ `Left | `Right | `All ] ->
+ sub:string ->
+ by:string ->
+ string ->
+ stringreplace ~which ~sub ~by s replaces some occurrences of sub by by in s.
is_sub ~sub ~sub_pos s ~pos ~sub_len returns true iff the substring of sub starting at position sub_pos and of length sub_len is a substring of s starting at position pos.
chop_prefix ~pre s removes pre from s if pre really is a prefix of s, returns None otherwise.
chop_suffix ~suf s removes suf from s if suf really is a suffix of s, returns None otherwise.
val lines_gen : string -> string genlines_gen s returns the gen of the lines of s (splits along '\n').
val lines_iter : string -> string iterlines_iter s returns the iter of the lines of s (splits along '\n').
lines_seq s returns the Seq.t of the lines of s (splits along '\n').
val concat_gen : sep:string -> string gen -> stringconcat_gen ~sep gen concatenates all strings of gen, separated with sep.
concat_seq ~sep seq concatenates all strings of seq, separated with sep.
val concat_iter : sep:string -> string iter -> stringconcat_iter ~sep iter concatenates all strings of iter, separated with sep.
val unlines_gen : string gen -> stringunlines_gen gen concatenates all strings of gen, separated with '\n'.
val unlines_iter : string iter -> stringunlines_iter iter concatenates all strings of iter, separated with '\n'.
unlines_seq seq concatenates all strings of seq, separated with '\n'.
set s i c creates a new string which is a copy of s, except for index i, which becomes c.
iter f s applies function f on each character of s. Alias to String.iter.
filter_map f s calls (f a0) (f a1) … (f an) where a0 … an are the characters of s. It returns the string of characters ci such as f ai = Some ci (when f returns None, the corresponding element of s is discarded).
filter f s discards characters of s not satisfying f.
uniq eq s remove consecutive duplicate characters in s.
flat_map ~sep f s maps each chars of s to a string, then concatenates them all.
for_all f s is true iff all characters of s satisfy the predicate f.
exists f s is true iff some character of s satisfy the predicate f.
drop_while f s discards any characters of s starting from the left, up to the first character c not satisfying f c.
rdrop_while f s discards any characters of s starting from the right, up to the first character c not satisfying f c.
iter2 f s1 s2 iterates on pairs of chars.
iteri2 f s1 s2 iterates on pairs of chars with their index.
fold2 f init s1 s2 folds on pairs of chars.
for_all2 f s1 s2 returns true iff all pairs of chars satisfy the predicate f.
exists2 f s1 s2 returns true iff a pair of chars satisfy the predicate f.
Those functions are deprecated in String since 4.03, so we provide a stable alias for them even in older versions.
equal_caseless s1 s2 compares s1 and s2 without respect to ascii lowercase.
Same as of_hex but fails harder.
A relatively efficient algorithm for finding sub-strings.
module Find : sig ... endmodule Split : sig ... endsplit_on_char by s splits the string s along the given char by.
split ~by s splits the string s along the given string by. Alias to Split.list_cpy.
compare_versions s1 s2 compares version strings s1 and s2, considering that numbers are above text.
compare_natural s1 s2 is the Natural Sort Order, comparing chunks of digits as natural numbers. https://en.wikipedia.org/wiki/Natural_sort_order
edit_distance ~cutoff s1 s2 is the edition distance between the two strings s1 and s2. This satisfies the classical distance axioms: it is always positive, symmetric, and satisfies the formula distance s1 s2 + distance s2 s3 >= distance s1 s3.
module Infix : sig ... endCCStringLabels.Findval compile : string -> [ `Direct ] patternval rcompile : string -> [ `Reverse ] patternval find : ?start:int -> pattern:[ `Direct ] pattern -> string -> intfind ?start ~pattern s searches for pattern in the string s, left-to-right.
val rfind : ?start:int -> pattern:[ `Reverse ] pattern -> string -> intrfind ?start ~pattern s searches for pattern in the string s, right-to-left.
CCStringLabels.InfixCCStringLabels.SplitSpecification of what to do with empty blocks, as in split ~by:"-" "-a-b-".
{first=false; last=false} will return ""; "a"; "b"; ""{first=true; last=false} will return "a"; "b" ""{first=false; last=true} will return ""; "a"; "b"{first=true; last=true} will return "a"; "b"The default value of all remaining functions is Drop_none.
val no_drop : drop_if_emptyno_drop does not drop any group, even empty and on borders.
val list_ :
+ ?drop:drop_if_empty ->
+ by:string ->
+ string ->
+ (string * int * int) listlist_ ?drop ~by s splits the given string s along the given separator by. Should only be used with very small separators, otherwise use Containers_string.KMP.
val gen :
+ ?drop:drop_if_empty ->
+ by:string ->
+ string ->
+ (string * int * int) gengen ?drop ~by s splits the given string s along the given separator by. Returns a gen of slices.
val iter :
+ ?drop:drop_if_empty ->
+ by:string ->
+ string ->
+ (string * int * int) iteriter ?drop ~by s splits the given string s along the given separator by. Returns an iter of slices.
val seq :
+ ?drop:drop_if_empty ->
+ by:string ->
+ string ->
+ (string * int * int) Stdlib.Seq.tseq ?drop ~by s splits the given string s along the given separator by. Returns a Seq.t of slices. Renamed from std_seq since 3.0.
Those split functions actually copy the substrings, which can be more convenient but less efficient in general.
val list_cpy : ?drop:drop_if_empty -> by:string -> string -> string listlist_cpy ?drop ~by s splits the given string s along the given separator by. Returns a list of strings.
val gen_cpy : ?drop:drop_if_empty -> by:string -> string -> string gengen_cpy ?drop ~by s splits the given string s along the given separator by. Returns a gen of strings.
val iter_cpy : ?drop:drop_if_empty -> by:string -> string -> string iteriter_cpy ?drop ~by s splits the given string s along the given separator by. Returns an iter of strings.
val seq_cpy : ?drop:drop_if_empty -> by:string -> string -> string Stdlib.Seq.tseq_cpy ?drop ~by s splits the given string s along the given separator by. Returns a Seq.t of strings. Renamed from std_seq_cpy since 3.0.
left ~by s splits on the first occurrence of by from the leftmost part of the string s.
left_exn ~by s splits on the first occurrence of by from the leftmost part of the string s.
right ~by s splits on the first occurrence of by from the rightmost part of the string s.
CCStringLabelsBasic String Utils (Labeled version of CCString)
include module type of struct include Stdlib.StringLabels endval to_seqi : t -> (int * char) Stdlib.Seq.tval get_utf_8_uchar : t -> int -> Stdlib.Uchar.utf_decodeval is_valid_utf_8 : t -> boolval get_utf_16be_uchar : t -> int -> Stdlib.Uchar.utf_decodeval is_valid_utf_16be : t -> boolval get_utf_16le_uchar : t -> int -> Stdlib.Uchar.utf_decodeval is_valid_utf_16le : t -> boolval length : t -> intlength s returns the length (number of characters) of the given string s.
val blit :
+ src:t ->
+ src_pos:int ->
+ dst:Stdlib.Bytes.t ->
+ dst_pos:int ->
+ len:int ->
+ unitblit ~src ~src_pos ~dst ~dst_pos ~len copies len characters from string src starting at character indice src_pos, to the Bytes sequence dst starting at character indice dst_pos. Like String.blit. Compatible with the -safe-string option.
val fold : f:( 'a -> char -> 'a ) -> init:'a -> t -> 'afold ~f ~init s folds on chars by increasing index. Computes f(… (f (f init s.[0]) s.[1]) …) s.[n-1].
val foldi : f:( 'a -> int -> char -> 'a ) -> 'a -> t -> 'afoldi ~f init s is just like fold, but it also passes in the index of each chars as second argument to the folded function f.
val to_seq : t -> char Stdlib.Seq.tto_seq s returns the Seq.t of characters contained in the string s. Renamed from to std_seq since 3.0.
val to_list : t -> char listto_list s returns the list of characters contained in the string s.
val pp_buf : Stdlib.Buffer.t -> t -> unitpp_buf buf s prints s to the buffer buf. Renamed from pp since 2.0.
val pp : Stdlib.Format.formatter -> t -> unitpp f s prints the string s within quotes to the formatter f. Renamed from print since 2.0.
compare s1 s2 compares the strings s1 and s2 and returns an integer that indicates their relative position in the sort order.
pad ?side ?c n s ensures that the string s is at least n bytes long, and pads it on the side with c if it's not the case.
val of_gen : char gen -> stringof_gen gen converts a gen of characters to a string.
val of_iter : char iter -> stringof_iter iter converts an iter of characters to a string.
of_seq seq converts a seq of characters to a string. Renamed from of_std_seq since 3.0.
to_array s returns the array of characters contained in the string s.
find ?start ~sub s returns the starting index of the first occurrence of sub within s or -1.
val find_all : ?start:int -> sub:string -> string -> int genfind_all ?start ~sub s finds all occurrences of sub in s, even overlapping instances and returns them in a generator gen.
find_all_l ?start ~sub s finds all occurrences of sub in s and returns them in a list.
mem ?start ~sub s is true iff sub is a substring of s.
rfind ~sub s finds sub in string s from the right, returns its first index or -1. Should only be used with very small sub.
val replace :
+ ?which:[ `Left | `Right | `All ] ->
+ sub:string ->
+ by:string ->
+ string ->
+ stringreplace ?which ~sub ~by s replaces some occurrences of sub by by in s.
is_sub ~sub ~sub_pos s ~pos ~sub_len returns true iff the substring of sub starting at position sub_pos and of length sub_len is a substring of s starting at position pos.
chop_prefix ~pre s removes pre from s if pre really is a prefix of s, returns None otherwise.
chop_suffix ~suf s removes suf from s if suf really is a suffix of s, returns None otherwise.
val lines_gen : string -> string genlines_gen s returns a generator gen of the lines of s (splits along '\n').
val lines_iter : string -> string iterlines_iter s returns the iter of the lines of s (splits along '\n').
lines_seq s returns the Seq.t of the lines of s (splits along '\n').
val concat_iter : sep:string -> string iter -> stringconcat_iter ~sep iter concatenates all strings of iter, separated with sep.
val concat_gen : sep:string -> string gen -> stringconcat_gen ~sep gen concatenates all strings of gen, separated with sep.
concat_seq ~sep seq concatenates all strings of seq, separated with sep.
val unlines_gen : string gen -> stringunlines_gen gen concatenates all strings of gen, separated with '\n'.
val unlines_iter : string iter -> stringunlines_iter iter concatenates all strings of iter, separated with '\n'.
unlines_seq seq concatenates all strings of seq, separated with '\n'.
set s i c creates a new string which is a copy of s, except for index i, which becomes c.
iter ~f s applies function f on each character of s. Alias to String.iter.
filter_map ~f s calls (f a0) (f a1) … (f an) where a0 … an are the characters of s. It returns the string of characters ci such as f ai = Some ci (when f returns None, the corresponding element of s is discarded).
filter ~f s discards characters of s not satisfying f.
uniq ~eq s remove consecutive duplicate characters in s.
flat_map ?sep ~f s maps each chars of s to a string, then concatenates them all.
for_all ~f s is true iff all characters of s satisfy the predicate f.
exists ~f s is true iff some character of s satisfy the predicate f.
drop_while ~f s discards any characters of s starting from the left, up to the first character c not satisfying f c.
rdrop_while ~f s discards any characters of s starting from the right, up to the first character c not satisfying f c.
map2 ~f s1 s2 maps pairs of chars.
iter2 ~f s1 s2 iterates on pairs of chars.
iteri2 ~f s1 s2 iterates on pairs of chars with their index.
fold2 ~f ~init s1 s2 folds on pairs of chars.
for_all2 ~f s1 s2 returns true iff all pairs of chars satisfy the predicate f.
exists2 ~f s1 s2 returns true iff a pair of chars satisfy the predicate f.
Those functions are deprecated in String since 4.03, so we provide a stable alias for them even in older versions.
capitalize_ascii s returns a copy of s with the first character set to uppercase using the US-ASCII character set. See String.
uncapitalize_ascii s returns a copy of s with the first character set to lowercase using the US-ASCII character set. See String.
uppercase_ascii s returns a copy of s with all lowercase letters translated to uppercase using the US-ASCII character set. See String.
lowercase_ascii s returns a copy of s with all uppercase letters translated to lowercase using the US-ASCII character set. See String.
equal_caseless s1 s2 compares s1 and s2 without respect to ascii lowercase.
Same as of_hex but fails harder.
A relatively efficient algorithm for finding sub-strings.
module Find : sig ... endmodule Split : sig ... endsplit_on_char ~by s splits the string s along the given char by.
split ~by s splits the string s along the given string by. Alias to Split.list_cpy.
compare_versions s1 s2 compares version strings s1 and s2, considering that numbers are above text.
compare_natural s1 s2 is the Natural Sort Order, comparing chunks of digits as natural numbers. https://en.wikipedia.org/wiki/Natural_sort_order
edit_distance ?cutoff s1 s2 is the edition distance between the two strings s1 and s2. This satisfies the classical distance axioms: it is always positive, symmetric, and satisfies the formula distance s1 s2 + distance s2 s3 >= distance s1 s3.
module Infix : sig ... endCCUnitCCUnix.Infixval (?|) : ( 'a, Stdlib.Buffer.t, unit, call_result ) Stdlib.format4 -> 'aInfix version of call.
val (?|&) :
+ ( 'a, Stdlib.Buffer.t, unit, async_call_result ) Stdlib.format4 ->
+ 'aInfix version of async_call.
CCUnixSome useful functions built on top of Unix.
status: unstable
val call_full :
+ ?bufsize:int ->
+ ?stdin:[ `Gen of string gen | `Str of string ] ->
+ ?env:string array ->
+ ( 'a, Stdlib.Buffer.t, unit, call_result ) Stdlib.format4 ->
+ 'acall_full cmd wraps the result of Unix.open_process_full cmd into an object. It reads the full stdout and stderr of the subprocess before returning. cmd can be a format string as in Printf.
val call :
+ ?bufsize:int ->
+ ?stdin:[ `Gen of string gen | `Str of string ] ->
+ ?env:string array ->
+ ( 'a, Stdlib.Buffer.t, unit, string * string * int ) Stdlib.format4 ->
+ 'acall cmd is similar to call_full but returns a tuple stdout, stderr, errcode instead of an object.
val call_stdout :
+ ?bufsize:int ->
+ ?stdin:[ `Gen of string gen | `Str of string ] ->
+ ?env:string array ->
+ ( 'a, Stdlib.Buffer.t, unit, string ) Stdlib.format4 ->
+ 'atype async_call_result =
+ < stdout : line gen
+ ; stderr : line gen
+ ; stdin : line -> unit
+ ; close_in : unit
+ ; close_err : unit
+ ; close_out : unit
+ ; close_all : unit
+ ; wait : Unix.process_status
+ ; wait_errcode : int >A subprocess for interactive usage (read/write channels line by line)
val async_call :
+ ?env:string array ->
+ ( 'a, Stdlib.Buffer.t, unit, async_call_result ) Stdlib.format4 ->
+ 'aSpawns a subprocess, like call, but the subprocess's channels are line generators and line sinks (for stdin). If p is async_call "cmd", then p#wait waits for the subprocess to die. Channels can be closed independently.
val with_in :
+ ?mode:int ->
+ ?flags:Unix.open_flag list ->
+ string ->
+ f:( Stdlib.in_channel -> 'a ) ->
+ 'aOpen an input file with the given optional flag list, calls the function on the input channel. When the function raises or returns, the channel is closed.
val with_out :
+ ?mode:int ->
+ ?flags:Unix.open_flag list ->
+ string ->
+ f:( Stdlib.out_channel -> 'a ) ->
+ 'aSame as with_in but for an output channel.
Open a shell command in a subprocess and obtain a handle to its stdout.
CCUnix.with_process_in "ls /tmp" ~f:CCIO.read_lines_l;;Open a shell command in a subprocess and obtain a handle to its stdin.
type process_full =
+ < stdin : Stdlib.out_channel
+ ; stdout : Stdlib.in_channel
+ ; stderr : Stdlib.in_channel
+ ; close : Unix.process_status >Handle to a subprocess.
val with_process_full :
+ ?env:string array ->
+ string ->
+ f:( process_full -> 'a ) ->
+ 'aOpen a subprocess and obtain a handle to its channels.
On unix, call Unix.setsid() to make sure subprocesses die at the same time as the current process. Does nothing on windows. Idempotent: it can be called several times but will only have effects, if any, the first time.
val with_connection :
+ Unix.sockaddr ->
+ f:( Stdlib.in_channel -> Stdlib.out_channel -> 'a ) ->
+ 'aWrap Unix.open_connection with a handler.
val establish_server :
+ Unix.sockaddr ->
+ f:( Stdlib.in_channel -> Stdlib.out_channel -> _ ) ->
+ unitListen on the address and calls the handler in a blocking fashion. Using Thread is recommended if handlers might take time. The callback should raise ExitServer to stop the loop.
with_file_lock ~kind filename f puts a lock on the offset 0 of the file named filename, calls f and returns its result after the file is unlocked. If f () raises an exception the exception is re-raised after the file is unlocked.
module Infix : sig ... endinclude module type of Infixval (?|) : ( 'a, Stdlib.Buffer.t, unit, call_result ) Stdlib.format4 -> 'aInfix version of call.
val (?|&) :
+ ( 'a, Stdlib.Buffer.t, unit, async_call_result ) Stdlib.format4 ->
+ 'aInfix version of async_call.
CCUtf8_stringUnicode String, in UTF8
A unicode string represented by a utf8 bytestring. This representation is convenient for manipulating normal OCaml strings that are encoded in UTF8.
We perform only basic decoding and encoding between codepoints and bytestrings. For more elaborate operations, please use the excellent Uutf.
status: experimental
val hash : t -> intval pp : Stdlib.Format.formatter -> t -> unitval to_string : t -> stringIdentity.
Iter of unicode codepoints. Renamed from to_std_seq since 3.0.
val n_chars : t -> intNumber of characters.
val n_bytes : t -> intNumber of bytes.
val empty : tEmpty string.
concat sep l concatenates each string in l, inserting sep in between each string. Similar to String.concat.
Build a string from unicode codepoints Renamed from of_std_seq since 3.0.
Translate the unicode codepoint to a list of utf-8 bytes. This can be used, for example, in combination with Buffer.add_char on a pre-allocated buffer to add the bytes one by one (despite its name, Buffer.add_char takes individual bytes, not unicode codepoints).
val of_string_exn : string -> tValidate string by checking it is valid UTF8.
val of_string : string -> t optionSafe version of of_string_exn.
val unsafe_of_string : string -> tConversion from a string without validating. CAUTION this is unsafe and can break all the other functions in this module. Use only if you're sure the string is valid UTF8. Upon iteration, if an invalid substring is met, Malformed will be raised.
CCVectorGrowable, mutable vector
Mutability is rw (read-write) or ro (read-only).
Make an immutable vector (no copy! Don't use the old version).
Create a new vector, the value is used to enforce the type the new vector.
val return : 'a -> ( 'a, 'mut ) tSingleton vector.
val make : int -> 'a -> ( 'a, 'mut ) tmake n x makes a vector of size n, filled with x.
val init : int -> ( int -> 'a ) -> ( 'a, 'mut ) tInit the vector with the given function and size.
Clear the content of the vector. This ensures that length v = 0 but the underlying array is kept, and possibly references to former elements, which are therefore not garbage collectible.
Clear the content of the vector, and deallocate the underlying array, removing references to all the elements. The elements can be collected.
Hint to the vector that it should have at least the given capacity. This does not affect length v.
Hint to the vector that it should have at least the given capacity. Just a hint, will not be enforced if the vector is empty and init is not provided.
val is_empty : ( 'a, _ ) t -> boolIs the vector empty?
resize_with vec f size resizes vector vec up to size, fills vector with calls to f on indexes [vec.size-1.. size - 1]. The contents and size of vec are untouched if size is inferior or equal to length vec.
resize_with_init vec init size resizes vector vec up to size, fills vector with calls to init on indexes [length vec -1.. size - 1]. The contents and size of vec are untouched if size is inferior or equal to length vec.
Append content of iterator. Renamed from append_std_seq since 3.0.
val top : ( 'a, _ ) t -> 'a optionTop element, if present.
val top_exn : ( 'a, _ ) t -> 'aTop element, if present.
Truncate to the given size (remove elements above this size). Does nothing if the parameter is bigger than the current size. truncate was called shrink.
val shrink_to_fit : ( 'a, _ ) t -> unitShrink internal array to fit the size of the vector
val member : eq:( 'a -> 'a -> bool ) -> 'a -> ( 'a, _ ) t -> boolIs the element a member of the vector?
Sort the vector, returning a copy of it that is sorted w.r.t the given ordering. The vector itself is unchanged. The underlying array of the new vector can be smaller than the original one.
Sort the vector in place (modifying it). This function change the size of the underlying array.
Sort the array and remove duplicates, in place (e.g. modifying the vector itself).
val iter : ( 'a -> unit ) -> ( 'a, _ ) t -> unitIterate on the vector's content.
val iteri : ( int -> 'a -> unit ) -> ( 'a, _ ) t -> unitIterate on the vector, with indexes.
Map elements of the vector, yielding a new vector.
map f v is just like map, but it also passes in the index of each element as the first argument to the function f.
val map_in_place : ( 'a -> 'a ) -> ( 'a, _ ) t -> unitMap elements of the vector in place
Filter elements from the vector. filter p v leaves v unchanged but returns a new vector that only contains elements of v satisfying p.
Filter elements from the vector in place.
val fold : ( 'b -> 'a -> 'b ) -> 'b -> ( 'a, _ ) t -> 'bFold on elements of the vector
val exists : ( 'a -> bool ) -> ( 'a, _ ) t -> boolExistential test (is there an element that satisfies the predicate?).
val for_all : ( 'a -> bool ) -> ( 'a, _ ) t -> boolUniversal test (do all the elements satisfy the predicate?).
val find : ( 'a -> bool ) -> ( 'a, _ ) t -> 'a optionFind an element that satisfies the predicate.
val find_exn : ( 'a -> bool ) -> ( 'a, _ ) t -> 'aFind an element that satisfies the predicate, or
val find_map : ( 'a -> 'b option ) -> ( 'a, _ ) t -> 'b optionfind_map f v returns the first Some y = f x for x in v, or None if f x = None for each x in v.
Map elements with a function, possibly filtering some of them out.
val filter_map_in_place : ( 'a -> 'a option ) -> ( 'a, _ ) t -> unitFilter-map elements of the vector in place
Map each element to a sub-vector.
Like flat_map, but using Seq for intermediate collections. Renamed from flat_map_std_seq since 3.0.
Like flat_map, but using list for intermediate collections.
All combinaisons of tuples from the two vectors are passed to the function.
val get : ( 'a, _ ) t -> int -> 'aAccess element by its index, or
remove_and_shift v i remove the i-th element from v. Move elements that are after the i-th in v, in linear time. Preserve the order of the elements in v. See remove_unordered for constant time removal function that doesn't preserve the order of elements.
remove_unordered v i remove the i-th element from v. Does NOT preserve the order of the elements in v (might swap with the last element). See remove_and_shift if you want to keep the ordering.
insert v i x insert the given element at index i. Elements at location i and later are first shifted over in linear time before inserting x. Preserve the order of elements in v.
val rev_iter : ( 'a -> unit ) -> ( 'a, _ ) t -> unitrev_iter f a is the same as iter f (rev a), only more efficient.
val size : ( 'a, _ ) t -> intNumber of elements in the vector.
val capacity : ( _, _ ) t -> intNumber of elements the vector can contain without being resized.
Access the underlying shared array (do not modify!). unsafe_get_array v is longer than size v, but elements at higher index than size v are undefined (do not access!).
val (--) : int -> int -> ( int, 'mut ) tRange of integers, either ascending or descending (both included, therefore the result is never empty). Example: 1 -- 10 returns the vector [1;2;3;4;5;6;7;8;9;10].
val (--^) : int -> int -> ( int, 'mut ) tRange of integers, either ascending or descending, but excluding right. Example: 1 --^ 10 returns the vector [1;2;3;4;5;6;7;8;9].
val of_array : 'a array -> ( 'a, 'mut ) tof_array a returns a vector corresponding to the array a. Operates in O(n) time.
val of_list : 'a list -> ( 'a, 'mut ) tval to_array : ( 'a, _ ) t -> 'a arrayto_array v returns an array corresponding to the vector v.
val to_list : ( 'a, _ ) t -> 'a listReturn a list with the elements contained in the vector.
Convert an Iterator to a vector. Renamed from of_std_seq since 3.0.
to_iter_rev v returns the sequence of elements of v in reverse order, that is, the last elements of v are iterated on first.
val to_seq : ( 'a, _ ) t -> 'a Stdlib.Seq.tReturn an iterator with the elements contained in the vector. Renamed from to_std_seq since 3.0.
val to_seq_rev : ( 'a, _ ) t -> 'a Stdlib.Seq.tto_seq v returns the sequence of elements of v in reverse order, that is, the last elements of v are iterated on first. Renamed from to_std_seq since 3.0.
Vector as an array slice. By doing it we expose the internal array, so be careful!.
slice_iter v start len is the sequence of elements from v.(start) to v.(start+len-1).
val to_string :
+ ?start:string ->
+ ?stop:string ->
+ ?sep:string ->
+ ( 'a -> string ) ->
+ ( 'a, _ ) t ->
+ stringPrint the vector in a string
val pp :
+ ?pp_start:unit printer ->
+ ?pp_stop:unit printer ->
+ ?pp_sep:unit printer ->
+ 'a printer ->
+ ( 'a, _ ) t printerpp ~pp_start ~pp_stop ~pp_sep pp_item ppf v formats the vector v on ppf. Each element is formatted with pp_item, pp_start is called at the beginning, pp_stop is called at the end, pp_sep is called between each elements. By defaults pp_start and pp_stop does nothing and pp_sep defaults to (fun out -> Format.fprintf out ",@ ").
Hashtbl.Makeval create : int -> 'a tval clear : 'a t -> unitval reset : 'a t -> unitval length : 'a t -> intval stats : 'a t -> Stdlib__Hashtbl.statisticsval to_seq_values : 'a t -> 'a Stdlib.Seq.tHashtbl.MakeSeededmodule H : SeededHashedTypetype key = H.tval create : ?random:bool -> int -> 'a tval clear : 'a t -> unitval reset : 'a t -> unitval length : 'a t -> intval stats : 'a t -> statisticsval to_seq_values : 'a t -> 'a Stdlib.Seq.tContainers.Hashtblinclude module type of Stdlib.Hashtbl
+ with type statistics = Stdlib.Hashtbl.statistics
+ and module Make = Stdlib.Hashtbl.Make
+ and type ('a, 'b) t = ( 'a, 'b ) Stdlib.Hashtbl.tval create : ?random:bool -> int -> ( 'a, 'b ) tval clear : ( 'a, 'b ) t -> unitval reset : ( 'a, 'b ) t -> unitval add : ( 'a, 'b ) t -> 'a -> 'b -> unitval find : ( 'a, 'b ) t -> 'a -> 'bval find_opt : ( 'a, 'b ) t -> 'a -> 'b optionval find_all : ( 'a, 'b ) t -> 'a -> 'b listval mem : ( 'a, 'b ) t -> 'a -> boolval remove : ( 'a, 'b ) t -> 'a -> unitval replace : ( 'a, 'b ) t -> 'a -> 'b -> unitval iter : ( 'a -> 'b -> unit ) -> ( 'a, 'b ) t -> unitval filter_map_inplace : ( 'a -> 'b -> 'b option ) -> ( 'a, 'b ) t -> unitval fold : ( 'a -> 'b -> 'c -> 'c ) -> ( 'a, 'b ) t -> 'c -> 'cval length : ( 'a, 'b ) t -> intval stats : ( 'a, 'b ) t -> statisticsval to_seq : ( 'a, 'b ) t -> ('a * 'b) Stdlib.Seq.tval to_seq_keys : ( 'a, 'b ) t -> 'a Stdlib.Seq.tval to_seq_values : ( 'a, 'b ) t -> 'b Stdlib.Seq.tval replace_seq : ( 'a, 'b ) t -> ('a * 'b) Stdlib.Seq.t -> unitmodule type HashedType = sig ... endmodule type S = sig ... endmodule type SeededHashedType = sig ... endmodule type SeededS = sig ... endmodule MakeSeeded (H : SeededHashedType) : sig ... endinclude module type of struct include CCHashtbl.Poly endget tbl k finds a binding for the key k if present, or returns None if no value is found. Safe version of Hashtbl.find.
get_or tbl k ~default returns the value associated to k if present, and returns default otherwise (if k doesn't belong in tbl).
val keys : ( 'a, 'b ) Stdlib.Hashtbl.t -> 'a CCHashtbl.iterkeys tbl f iterates on keys (similar order as Hashtbl.iter).
val values : ( 'a, 'b ) Stdlib.Hashtbl.t -> 'b CCHashtbl.itervalues tbl f iterates on values in the table tbl.
keys_list tbl is the list of keys in tbl. If the key is in the Hashtable multiple times, all occurrences will be returned.
values_list tbl is the list of values in tbl.
map_list f tbl maps on a tbl's items. Collect into a list.
incr ?by tbl x increments or initializes the counter associated with x. If get tbl x = None, then after update, get tbl x = Some 1; otherwise, if get tbl x = Some n, now get tbl x = Some (n+1).
decr ?by tbl x is like incr but subtract 1 (or the value of by). If the value reaches 0, the key is removed from the table. This does nothing if the key is not already present in the table.
val to_iter : ( 'a, 'b ) Stdlib.Hashtbl.t -> ('a * 'b) CCHashtbl.iterIterate on bindings in the table.
add_list tbl x y adds y to the list x is bound to. If x is not bound, it becomes bound to y.
val add_iter : ( 'a, 'b ) Stdlib.Hashtbl.t -> ('a * 'b) CCHashtbl.iter -> unitAdd the corresponding pairs to the table, using Hashtbl.add.
val add_iter_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ( 'a, 'b ) Stdlib.Hashtbl.t ->
+ ('a * 'b) CCHashtbl.iter ->
+ unitAdd the corresponding pairs to the table, using Hashtbl.add. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
Add the corresponding pairs to the table, using Hashtbl.add. Renamed from add_std_seq since 3.0.
val add_seq_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ( 'a, 'b ) Stdlib.Hashtbl.t ->
+ ('a * 'b) Stdlib.Seq.t ->
+ unitAdd the corresponding pairs to the table. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
val of_iter : ('a * 'b) CCHashtbl.iter -> ( 'a, 'b ) Stdlib.Hashtbl.tFrom the given bindings, added in order.
val of_iter_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ('a * 'b) CCHashtbl.iter ->
+ ( 'a, 'b ) Stdlib.Hashtbl.tFrom the given bindings, added in order. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
From the given bindings, added in order. Renamed from of_std_seq since 3.0.
val of_seq_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ('a * 'b) Stdlib.Seq.t ->
+ ( 'a, 'b ) Stdlib.Hashtbl.tFrom the given bindings, added in order. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
val add_iter_count : ( 'a, int ) Stdlib.Hashtbl.t -> 'a CCHashtbl.iter -> unitadd_iter_count tbl i increments the count of each element of i by calling incr. This is useful for counting how many times each element of i occurs.
add_seq_count tbl seq increments the count of each element of seq by calling incr. This is useful for counting how many times each element of seq occurs. Renamed from add_std_seq_count since 3.0.
val of_iter_count : 'a CCHashtbl.iter -> ( 'a, int ) Stdlib.Hashtbl.tLike add_seq_count, but allocates a new table and returns it.
Like add_seq_count, but allocates a new table and returns it. Renamed from of_std_seq_count since 3.0.
to_list tbl returns the list of (key,value) bindings (order unspecified).
of_list l builds a table from the given list l of bindings k_i -> v_i, added in order using add. If a key occurs several times, it will be added several times, and the visible binding will be the last one.
val of_list_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ('a * 'b) list ->
+ ( 'a, 'b ) Stdlib.Hashtbl.tFrom the given bindings, added in order. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
val update :
+ ( 'a, 'b ) Stdlib.Hashtbl.t ->
+ f:( 'a -> 'b option -> 'b option ) ->
+ k:'a ->
+ unitupdate tbl ~f ~k updates key k by calling f k (Some v) if k was mapped to v, or f k None otherwise; if the call returns None then k is removed/stays removed, if the call returns Some v' then the binding k -> v' is inserted using Hashtbl.replace.
get_or_add tbl ~k ~f finds and returns the binding of k in tbl, if it exists. If it does not exist, then f k is called to obtain a new binding v; k -> v is added to tbl and v is returned.
val pp :
+ ?pp_start:unit CCHashtbl.printer ->
+ ?pp_stop:unit CCHashtbl.printer ->
+ ?pp_sep:unit CCHashtbl.printer ->
+ ?pp_arrow:unit CCHashtbl.printer ->
+ 'a CCHashtbl.printer ->
+ 'b CCHashtbl.printer ->
+ ( 'a, 'b ) Stdlib.Hashtbl.t CCHashtbl.printerpp ~pp_start ~pp_stop ~pp_sep ~pp arrow pp_k pp_v returns a table printer given a pp_k printer for individual key and a pp_v printer for individual value. pp_start and pp_stop control the opening and closing delimiters, by default print nothing. pp_sep control the separator between binding. pp_arrow control the arrow between the key and value. Renamed from print since 2.0.
module type S' = CCHashtbl.Smodule Make' = CCHashtbl.MakeHashtbl.HashedTypeHashtbl.Sval create : int -> 'a tval clear : 'a t -> unitval reset : 'a t -> unitval length : 'a t -> intval stats : 'a t -> statisticsval to_seq_values : 'a t -> 'a Stdlib.Seq.tHashtbl.SeededHashedTypeHashtbl.SeededSval create : ?random:bool -> int -> 'a tval clear : 'a t -> unitval reset : 'a t -> unitval length : 'a t -> intval stats : 'a t -> statisticsval to_seq_values : 'a t -> 'a Stdlib.Seq.tContainersDrop-In replacement to Stdlib
module Array = CCArraymodule Bool = CCBoolmodule Byte_buffer = CCByte_buffermodule Char = CCCharmodule Equal = CCEqualmodule Either = CCEithermodule Float = CCFloatmodule Format = CCFormatmodule Fun = CCFunmodule Hash = CCHashmodule Hashtbl : sig ... endmodule Heap = CCHeapmodule Int = CCIntmodule Int32 = CCInt32module Int64 = CCInt64module IO = CCIOmodule List = CCListmodule Map = CCMapmodule Nativeint = CCNativeintmodule Option = CCOptionmodule Ord = CCOrdmodule Pair = CCPairmodule Parse = CCParsemodule Random = CCRandommodule Ref = CCRefmodule Result = CCResultmodule Seq = CCSeqmodule Set = CCSetmodule String = CCStringmodule Vector = CCVectormodule Monomorphic = CCMonomorphicmodule Utf8_string = CCUtf8_stringmodule Unit = CCUnitmodule Atomic = CCAtomicmodule Sexp = CCSexpmodule Sexp_intf = CCSexp_intfmodule Canonical_sexp = CCCanonical_sexpmodule Stdlib = CCShims_.Stdlibinclude module type of struct include Monomorphic endHashtbl.Makeval create : int -> 'a tval clear : 'a t -> unitval reset : 'a t -> unitval length : 'a t -> intval stats : 'a t -> Stdlib__Hashtbl.statisticsval to_seq_values : 'a t -> 'a Stdlib.Seq.tHashtbl.MakeSeededmodule H : SeededHashedTypetype key = H.tval create : ?random:bool -> int -> 'a tval clear : 'a t -> unitval reset : 'a t -> unitval length : 'a t -> intval stats : 'a t -> statisticsval to_seq_values : 'a t -> 'a Stdlib.Seq.tContainersLabels.Hashtblinclude module type of Stdlib.Hashtbl
+ with type statistics = Stdlib.Hashtbl.statistics
+ and module Make = Stdlib.Hashtbl.Make
+ and type ('a, 'b) t = ( 'a, 'b ) Stdlib.Hashtbl.tval create : ?random:bool -> int -> ( 'a, 'b ) tval clear : ( 'a, 'b ) t -> unitval reset : ( 'a, 'b ) t -> unitval add : ( 'a, 'b ) t -> 'a -> 'b -> unitval find : ( 'a, 'b ) t -> 'a -> 'bval find_opt : ( 'a, 'b ) t -> 'a -> 'b optionval find_all : ( 'a, 'b ) t -> 'a -> 'b listval mem : ( 'a, 'b ) t -> 'a -> boolval remove : ( 'a, 'b ) t -> 'a -> unitval replace : ( 'a, 'b ) t -> 'a -> 'b -> unitval iter : ( 'a -> 'b -> unit ) -> ( 'a, 'b ) t -> unitval filter_map_inplace : ( 'a -> 'b -> 'b option ) -> ( 'a, 'b ) t -> unitval fold : ( 'a -> 'b -> 'c -> 'c ) -> ( 'a, 'b ) t -> 'c -> 'cval length : ( 'a, 'b ) t -> intval stats : ( 'a, 'b ) t -> statisticsval to_seq : ( 'a, 'b ) t -> ('a * 'b) Stdlib.Seq.tval to_seq_keys : ( 'a, 'b ) t -> 'a Stdlib.Seq.tval to_seq_values : ( 'a, 'b ) t -> 'b Stdlib.Seq.tval replace_seq : ( 'a, 'b ) t -> ('a * 'b) Stdlib.Seq.t -> unitmodule type HashedType = sig ... endmodule type S = sig ... endmodule type SeededHashedType = sig ... endmodule type SeededS = sig ... endmodule MakeSeeded (H : SeededHashedType) : sig ... endinclude module type of struct include CCHashtbl.Poly endget tbl k finds a binding for the key k if present, or returns None if no value is found. Safe version of Hashtbl.find.
get_or tbl k ~default returns the value associated to k if present, and returns default otherwise (if k doesn't belong in tbl).
val keys : ( 'a, 'b ) Stdlib.Hashtbl.t -> 'a CCHashtbl.iterkeys tbl f iterates on keys (similar order as Hashtbl.iter).
val values : ( 'a, 'b ) Stdlib.Hashtbl.t -> 'b CCHashtbl.itervalues tbl f iterates on values in the table tbl.
keys_list tbl is the list of keys in tbl. If the key is in the Hashtable multiple times, all occurrences will be returned.
values_list tbl is the list of values in tbl.
map_list f tbl maps on a tbl's items. Collect into a list.
incr ?by tbl x increments or initializes the counter associated with x. If get tbl x = None, then after update, get tbl x = Some 1; otherwise, if get tbl x = Some n, now get tbl x = Some (n+1).
decr ?by tbl x is like incr but subtract 1 (or the value of by). If the value reaches 0, the key is removed from the table. This does nothing if the key is not already present in the table.
val to_iter : ( 'a, 'b ) Stdlib.Hashtbl.t -> ('a * 'b) CCHashtbl.iterIterate on bindings in the table.
add_list tbl x y adds y to the list x is bound to. If x is not bound, it becomes bound to y.
val add_iter : ( 'a, 'b ) Stdlib.Hashtbl.t -> ('a * 'b) CCHashtbl.iter -> unitAdd the corresponding pairs to the table, using Hashtbl.add.
val add_iter_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ( 'a, 'b ) Stdlib.Hashtbl.t ->
+ ('a * 'b) CCHashtbl.iter ->
+ unitAdd the corresponding pairs to the table, using Hashtbl.add. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
Add the corresponding pairs to the table, using Hashtbl.add. Renamed from add_std_seq since 3.0.
val add_seq_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ( 'a, 'b ) Stdlib.Hashtbl.t ->
+ ('a * 'b) Stdlib.Seq.t ->
+ unitAdd the corresponding pairs to the table. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
val of_iter : ('a * 'b) CCHashtbl.iter -> ( 'a, 'b ) Stdlib.Hashtbl.tFrom the given bindings, added in order.
val of_iter_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ('a * 'b) CCHashtbl.iter ->
+ ( 'a, 'b ) Stdlib.Hashtbl.tFrom the given bindings, added in order. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
From the given bindings, added in order. Renamed from of_std_seq since 3.0.
val of_seq_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ('a * 'b) Stdlib.Seq.t ->
+ ( 'a, 'b ) Stdlib.Hashtbl.tFrom the given bindings, added in order. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
val add_iter_count : ( 'a, int ) Stdlib.Hashtbl.t -> 'a CCHashtbl.iter -> unitadd_iter_count tbl i increments the count of each element of i by calling incr. This is useful for counting how many times each element of i occurs.
add_seq_count tbl seq increments the count of each element of seq by calling incr. This is useful for counting how many times each element of seq occurs. Renamed from add_std_seq_count since 3.0.
val of_iter_count : 'a CCHashtbl.iter -> ( 'a, int ) Stdlib.Hashtbl.tLike add_seq_count, but allocates a new table and returns it.
Like add_seq_count, but allocates a new table and returns it. Renamed from of_std_seq_count since 3.0.
to_list tbl returns the list of (key,value) bindings (order unspecified).
of_list l builds a table from the given list l of bindings k_i -> v_i, added in order using add. If a key occurs several times, it will be added several times, and the visible binding will be the last one.
val of_list_with :
+ f:( 'a -> 'b -> 'b -> 'b ) ->
+ ('a * 'b) list ->
+ ( 'a, 'b ) Stdlib.Hashtbl.tFrom the given bindings, added in order. If a key occurs multiple times in the input, the values are combined using f in an unspecified order.
val update :
+ ( 'a, 'b ) Stdlib.Hashtbl.t ->
+ f:( 'a -> 'b option -> 'b option ) ->
+ k:'a ->
+ unitupdate tbl ~f ~k updates key k by calling f k (Some v) if k was mapped to v, or f k None otherwise; if the call returns None then k is removed/stays removed, if the call returns Some v' then the binding k -> v' is inserted using Hashtbl.replace.
get_or_add tbl ~k ~f finds and returns the binding of k in tbl, if it exists. If it does not exist, then f k is called to obtain a new binding v; k -> v is added to tbl and v is returned.
val pp :
+ ?pp_start:unit CCHashtbl.printer ->
+ ?pp_stop:unit CCHashtbl.printer ->
+ ?pp_sep:unit CCHashtbl.printer ->
+ ?pp_arrow:unit CCHashtbl.printer ->
+ 'a CCHashtbl.printer ->
+ 'b CCHashtbl.printer ->
+ ( 'a, 'b ) Stdlib.Hashtbl.t CCHashtbl.printerpp ~pp_start ~pp_stop ~pp_sep ~pp arrow pp_k pp_v returns a table printer given a pp_k printer for individual key and a pp_v printer for individual value. pp_start and pp_stop control the opening and closing delimiters, by default print nothing. pp_sep control the separator between binding. pp_arrow control the arrow between the key and value. Renamed from print since 2.0.
module type S' = CCHashtbl.Smodule Make' = CCHashtbl.MakeHashtbl.HashedTypeHashtbl.Sval create : int -> 'a tval clear : 'a t -> unitval reset : 'a t -> unitval length : 'a t -> intval stats : 'a t -> statisticsval to_seq_values : 'a t -> 'a Stdlib.Seq.tHashtbl.SeededHashedTypeHashtbl.SeededSval create : ?random:bool -> int -> 'a tval clear : 'a t -> unitval reset : 'a t -> unitval length : 'a t -> intval stats : 'a t -> statisticsval to_seq_values : 'a t -> 'a Stdlib.Seq.tContainersLabelsDrop-In replacement to Stdlib
module Array = CCArrayLabelsmodule Bool = CCBoolmodule Byte_buffer = CCByte_buffermodule Char = CCCharmodule Equal = CCEqualLabelsmodule Either = CCEithermodule Float = CCFloatmodule Format = CCFormatmodule Fun = CCFunmodule Hash = CCHashmodule Hashtbl : sig ... endmodule Heap = CCHeapmodule Int = CCIntmodule Int32 = CCInt32module Int64 = CCInt64module IO = CCIOmodule List = CCListLabelsmodule Map = CCMapmodule Nativeint = CCNativeintmodule Option = CCOptionmodule Ord = CCOrdmodule Pair = CCPairmodule Parse = CCParsemodule Random = CCRandommodule Ref = CCRefmodule Result = CCResultmodule Seq = CCSeqmodule Set = CCSetmodule String = CCStringLabelsmodule Vector = CCVectormodule Monomorphic = CCMonomorphicmodule Utf8_string = CCUtf8_stringmodule Sexp = CCSexpmodule Sexp_intf = CCSexp_intfmodule Stdlib = CCShims_.Stdlibinclude module type of struct include Monomorphic endContainers_bencode.DecodeDecoding
Containers_bencode.EncodeEncoding
val to_string : t -> stringval to_buffer : Stdlib.Buffer.t -> t -> unitval to_chan : Stdlib.out_channel -> t -> unitval to_fmt : Stdlib.Format.formatter -> t -> unitContainers_bencode.Str_mapContainers_bencodeBasic Bencode decoder/encoder.
See https://en.wikipedia.org/wiki/Bencode .
module Str_map : sig ... endval hash : t -> intval pp_debug : Stdlib.Format.formatter -> t -> unitPrinter for diagnostic/human consumption
val to_string_debug : t -> stringval int : int -> tval int64 : int64 -> tval string : string -> tmodule Encode : sig ... endEncoding
module Decode : sig ... endDecoding
Containers_cborCBOR encoder/decoder.
The type is chosen to be compatible with ocaml-cbor. See the RFC.
note this is experimental.
note this is only available on OCaml >= 4.08. Below that, the module is empty.
val pp_diagnostic : t CCFormat.printerval to_string_diagnostic : t -> stringval encode : ?buf:Stdlib.Buffer.t -> t -> stringval decode : string -> ( t, string ) Stdlib.resultContainers_codegen.Bitfieldval make : ?emit_failure_if_too_wide:bool -> name:string -> unit -> tMake a new bitfield with the given name.
val field_bit : t -> string -> unitfield_bit ty name adds a field of size 1 to the bitfield ty, with name name. The generate code will provide get/set for a boolean.
val field_int : t -> width:int -> string -> unitfield_int ty name ~width adds a field of size width to the bitfield with name name. The accessors will be for integers of width bits, and the setter might assert that the provided integer fits.
val total_width : t -> intTotal width in bits of the given bitfield.
Containers_codegen.Codetype t = codeval pp : t Fmt.printerval to_string : t -> stringval mk_pp : unit Fmt.printer -> tval mk_str : string -> tContainers_codegenThe code generator library is designed to be used from a build system (for example, from dune) to generate efficient code for features that are harder to provide at runtime.
The idea is that the build system should invoke some OCaml script that depends on containers.codegen; the script uses the DSL below to describe what code to generate (e.g. a description of a bitfield type) and emits a .ml file (and possibly a .mli file).
For example, the build script might contain:
module CG = Containers_codegen
+let () =
+ let module B = CG.Bitfield in
+ let b = B.make ~name:"t" () in
+ B.field_bit b "x";
+ B.field_bit b "y";
+ B.field_bit b "z";
+ B.field_int b ~width:5 "foo";
+
+ CG.emit_file "foo.mli" (B.gen_mli b);
+ CG.emit_file "foo.ml" (B.gen_ml b);
+ ()and this will produce foo.ml and foo.mli with a bitfield containing x, y, and z.
module Fmt = CCFormatmodule Code : sig ... endmodule Bitfield : sig ... endval emit_file : string -> code list -> unitemit_file file cs emits code fragments cs into the given file at path file
val emit_chan : Stdlib.out_channel -> code list -> unitval emit_string : code list -> stringMake.1-AContainers_scc.MakeContainers_sccmodule type ARG = sig ... endmodule type S = sig ... endval scc :
+ tbl:(module Stdlib.Hashtbl.S with type key = 'node) ->
+ graph:'graph ->
+ children:( 'graph -> 'node -> 'node iter ) ->
+ nodes:'node list ->
+ unit ->
+ 'node list listContainers_scc.ARGS.AContainers_scc.SContainers_topThis library exposes the following toplevel modules:
CCArray Array utilsCCArrayLabels Array utils (Labeled version of CCArray)CCAtomic CCBool Basic Bool functionsCCByte_buffer Byte buffer.CCCanonical_sexp Canonical S-expressionsCCChar Utils around charCCEither Either MonadCCEqual Equality CombinatorsCCEqualLabels Equality Combinators (Labeled version of CCEqual)CCFloat Basic operations on floating-point numbersCCFormat Helpers for FormatCCFun Basic operations on FunctionsCCHash Hash combinatorsCCHashtbl Extension to the standard HashtblCCHeap Leftist HeapsCCIO IO UtilsCCInt Basic Int functionsCCInt32 Helpers for 32-bit integers.CCInt64 Helpers for 64-bit integers.CCList Complements to ListCCListLabels Complements to ListLabelsCCMap Extensions of Standard MapCCNativeint Helpers for processor-native integersCCOpt Previous Option moduleCCOption Basic operations on the option type.CCOrd Order combinatorsCCPair Tuple FunctionsCCParse Very Simple Parser CombinatorsCCRandom Random GeneratorsCCRef Helpers for referencesCCResult Error MonadCCSeq Helpers for the standard Seq typeCCSet Wrapper around SetCCSexp Handling S-expressionsCCSexp_intf CCSexp_lex CCShims_ CCShims_syntax CCString Basic String UtilsCCStringLabels Basic String Utils (Labeled version of CCString)CCUnit CCUtf8_string Unicode String, in UTF8CCVector Growable, mutable vectorContainers Drop-In replacement to StdlibContainersLabels Drop-In replacement to StdlibThe entry point of this library is the module: Containers_bencode.
The entry point of this library is the module: Containers_cbor.
The entry point of this library is the module: Containers_codegen.
The entry point of this library is the module: CCMonomorphic.
The entry point of this library is the module: Containers_scc.
The entry point of this library is the module: Containers_top.
The entry point of this library is the module: CCUnix.