OCaml package documentation
+-
+
- less-power +
diff --git a/thread-counter/index.html b/thread-counter/index.html new file mode 100644 index 0000000..1d1dba1 --- /dev/null +++ b/thread-counter/index.html @@ -0,0 +1,19 @@ + + +
+Ast_check.Feature
val to_identifier : t -> string
Unique identifier for this feature.
val of_identifier : string -> t
Provides the feature corresponding to a unique identifier returned by to_identifier
.
Primitive
and Internal_name
, required to prevent circumventing restrictions.
Everything but Tail_mod_cons
.
val to_message : t -> string
Provide a message explaining why a feature is prohibited.
Ast_check
AST checker.
Tool to enforce restrictions on what syntax elements are allowed in OCaml code. Restricts use of the following class features and imperative elements:
while
loopsfor
loopsexternal
declarationsPackage__Module
)external
declarations and internal dune modules are forbidden, as they can be used to circumvent restrictions in the Stdlib
replacement. The sequence operator is not forbidden as there would be no point, a; b
can be trivially replaced by let _ = a in b
.
An executable is installed as lp-ast-check
. All files passed as arguments, and all .ml
files contained recursively in directories passed as arguments, are checked. Exits with code 0
if no violations are detected, 1
if violations are found, or 2
if an error occurs.
module Feature : sig ... end
type violation = {
location : Ppxlib.Location.t;
Location of the violation.
*)message : string option;
Error message.
*)feature : Feature.t;
Which prohibited feature was used.
*)}
A violation that occurred in the AST.
val ast_violations :
+ ?prohibited:Feature.Set.t ->
+ ?limit:int ->
+ Ppxlib.structure ->
+ violation list
Return a list of (up to limit
) violations for this AST.
val file_violations :
+ ?prohibited:Feature.Set.t ->
+ ?limit:int ->
+ string ->
+ violation list
As per ast_violations
, but first parse a file to an AST.
val path_violations :
+ ?follow:FileUtil.action_link ->
+ ?prohibited:Feature.Set.t ->
+ ?limit:int ->
+ ?check1:FileUtil.test_file ->
+ ?check:FileUtil.test_file ->
+ (violation list -> unit) ->
+ string ->
+ unit
As per file_violations
, but scan an entire directory (recursively). If the path designates a regular file, check the file if check1
matches (default: always); if a directory is scanned, check each file if check
matches (default: .ml
ending). Pass each (possibly empty) list of violations to the callback; see the note in pp_violation
.
The follow
argument (default: Follow
) only applies to directories; symlinks to files are always read.
val pp_violation_message : Stdlib.Format.formatter -> violation -> unit
val pp_violation : Stdlib.Format.formatter -> violation -> unit
Pretty-print a violation. Violations from a given file should be printed before the next file is parsed, otherwise no context from the source file will be output.
Breaks pretty-printing, this is a limitation of Location.print_report
Transformations intended directly for use with Ppxlib.
val ast_violations_transformation :
+ ?prohibited:Feature.Set.t ->
+ ?limit:int ->
+ Ppxlib.structure transformation
As per ast_violations
, but intended directly for use as a Ppxlib transformation. Errors are embedded as extension nodes in the returned AST.
val strip_signatures : Ppxlib.Ast.structure transformation
Removes module type annotations on modules. For example, these two definitions:
module M : S = struct ... end
+module M : S with type t = ... = struct ... end
Both become:
module M = struct ... end
Allows testing code that annotated module types but didn't think to add the with
constraint to expose the type.
Ast_check_ppx
Use the AST check as a PPX rewriter, with arguments. If further customization is needed, it's best to define a PPX directly in the given exercise's repository instead.
Ctx_util.Syntax
val let< : ('a, 'b, 'c) t -> ('a -> 'b) -> 'c
Let-syntax for with_context
Common.Ctx_util
Context managers, loosely inspired by Python
type ('a, 'b, 'c) t =
+ ('a -> ('b, Util.exn_info) Stdlib.result) ->
+ ('c, Util.exn_info) Stdlib.result
A context manager of type ('a, 'b, 'c) t
takes a continuation, and should feed the continuation a value of type 'a
. Once the continuation returns with either a Ok of 'b
or an exn_info
, the continuation should perform cleanup, and may suppress the exception by producing a suitable result (of type 'c
) instead. Often, 'b = 'c
.
This representation has the advantage that some existing functions library already implement this type (e.g. In_channel.with_open_text
).
val with_context : ('a, 'b, 'c) t -> ('d -> 'e) -> 'f
with_context cm f
runs f
in the context manager cm
module Syntax : sig ... end
val temp_file : ?temp_dir:string -> string -> string -> (string, 'a, 'b) t
As per Filename.temp_file
. Removes the temporary file upon completion.
val openfile :
+ string ->
+ Unix.open_flag list ->
+ Unix.file_perm ->
+ (Unix.file_descr, 'a, 'b) t
As per Unix.openfile
. Closes the file descriptor upon completion.
val set_signal : int -> Stdlib.Sys.signal_behavior -> (unit, 'a, 'b) t
As per Sys.set_signal
. Restores the previous signal behavior on completion.
val sigprocmask : Unix.sigprocmask_command -> int list -> (unit, 'a, 'b) t
As per Unix.sigprocmask
. Restores the previous mask on completion.
val timeout_unix :
+ ?timer:Unix.interval_timer ->
+ Mtime.span ->
+ (unit, 'a, 'b option) t
val timed : (unit, 'a, 'b * Mtime.span) t
val capture_exceptions :
+ ?filter:(exn -> bool) ->
+ unit ->
+ (unit, 'a, ('b, Util.exn_info) Stdlib.result) t
val empty_context : 'a -> ('b -> 'c) -> ('d, 'e, 'f) t
val empty_context' : 'a -> ('b, 'c, 'd) t
val optional_timeout_unix : ?timeout:Mtime.span -> (unit, 'a, 'b option) t
Common.P_run
Even higher-level wrapper around Unix.open_process
.
Waits for the given process or times out.
Timeout after duration
, sending signal
. If kill_after
is Some t
, then send SIGKILL
after waiting an additional t
.
val timeout :
+ ?signal:int ->
+ ?kill_after:Mtime.span ->
+ Mtime.span ->
+ timeout_description
type result = {
phase : phase;
What phase was the process in when it completed?
*)status : Unix.process_status;
What status did the process exit with?
*)stdout : string;
stderr : string;
elapsed : Mtime.span;
}
val result_is_ok : ?check_status:bool -> result -> bool
Did the subprocess exit normally? If check_status
is false
, ignore the exit code and check only for a timeout or signal
val pp_result :
+ ?hide_stdout:bool ->
+ ?hide_stderr:bool ->
+ ?command_line:string list ->
+ Stdlib.Format.formatter ->
+ result ->
+ unit
val p_run :
+ ?timeout:timeout_description ->
+ ?input:(Stdlib.Format.formatter -> unit) ->
+ ?args:string list ->
+ ?env:(string * string) list ->
+ string ->
+ result
Send the input
to command
with the given args
. Note: uses temporary files provided by Filename
.
Common.Path_util
Path and file-related utility functions.
like Sys.readdir
, but the returned entries are full paths
Checks that either p
is a regular file and condition
holds for it, or p
is a symlink to a regular file, and condition
holds for the symlink.
Common.Pp_util
More pretty-printing combinators.
Common.Util
Various utility functions.
Same as List.equal,butallowslistsofdifferenttypes
string_contains ~needle haystack
: does needle
exist as a substring of haystack
? Naive \mathcal{O}(nm)
implementation.
(~$ x) f
is f x
, e.g.: List.map (~$ 2) [List.nth ["a"; "b"; "c"]; String.sub "def" 1]
returns ["c"; "ef"]
Exception and its associated (raw) backtrace.
val raise_exn_info : exn_info -> 'a
val try_to_result : ('a -> 'b) -> 'c -> ('d, exn_info) Stdlib.result
val unresult_exn : ('a, exn_info) Stdlib.result -> 'b
val timeout_unix :
+ ?timer:Unix.interval_timer ->
+ Mtime.span ->
+ ('a -> 'b) ->
+ 'c ->
+ 'd option
timeout_unix t f
is Some (f ())
if the call to f
terminates within t
, otherwise None
. The timeout is triggered by a Unix signal.
Notes:
-
Does not interrupt f
until an allocation occurs, which may be never.-
Any existing Unix timer is suspended for the duration of the call to f
.+
If f
is interrupted, it will not be left running in the background.Common
Functionality common to multiple components.
module Util : sig ... end
Various utility functions.
module Pp_util : sig ... end
More pretty-printing combinators.
module Path_util : sig ... end
Path and file-related utility functions.
module Ctx_util : sig ... end
Context managers, loosely inspired by Python
module P_run : sig ... end
Even higher-level wrapper around Unix.open_process
.
Signature_builder.Ordered_set
val eval : ?eq:('a -> 'b -> bool) -> 'b list -> 'c t -> 'b list
Signature_builder.Parse
val ordered_set :
+ Ppxlib_ast.Ast.expression ->
+ Ppxlib_ast.Ast.expression Ordered_set.t
val kind : Ppxlib.expression -> kind
val signature_item_pat : Ppxlib_ast.Ast.expression -> signature_item_pat
val include_specs : Ppxlib.expression -> include_specs
val include_spec : allow_comma:bool -> Ppxlib.expression -> include_spec
Signature_builder
Library and PPX rewriter for building interfaces from existing interfaces by selectively adding and removing interface items.
type raw_signature_info = (string list * raw_signature) list
type signature_infos = (string * signature_info) list
val infos_add_signature :
+ string ->
+ string list ->
+ Ppxlib.signature ->
+ signature_infos ->
+ signature_infos
val info_add_signature :
+ string list ->
+ Ppxlib.signature ->
+ signature_info ->
+ signature_info
val infos_get_signature :
+ string ->
+ string list ->
+ signature_infos ->
+ Ppxlib.signature option
val info_get_signature :
+ string list ->
+ signature_info ->
+ Ppxlib.signature option
val load_raw_signature : raw_signature -> Ppxlib.signature
val load_signature_info : raw_signature_info -> signature_info
Stdlib
and Thread
/Event
val stdlib_signature_info : signature_info
val threads_signature_info : signature_info
module Ordered_set : sig ... end
type signature_item_pat = {
names : Ppxlib.longident_loc list;
kind : kind option;
loc : Ppxlib.location;
}
type include_specs = include_spec list
and include_spec =
| Include_from of {
from : Ppxlib.longident_loc;
items : signature_item_pat Ordered_set.t;
}
| Include_group of {
attributes : Ppxlib.attribute list;
items : include_specs;
}
module Parse : sig ... end
val match_lident_name : Ppxlib.longident -> signature_item_name -> bool
Does the given longident
(as a search pattern) match the given name?
val signature_item_names : Ppxlib.signature_item -> signature_item_name list
val match_kind : kind -> Ppxlib.signature_item -> bool
val match_signature_item_pat :
+ signature_item_pat ->
+ Ppxlib.signature_item ->
+ bool
val eval_pat_ordered_set :
+ Ppxlib.signature_item list ->
+ signature_item_pat Ordered_set.t ->
+ Ppxlib.signature_item list
val eval_include_specs :
+ signature_infos ->
+ include_specs ->
+ Ppxlib.signature_item list
val eval_include_spec :
+ signature_infos ->
+ include_spec ->
+ Ppxlib.signature_item list
val default_sig_infos : (string * signature_info) list
val ppx_include :
+ ?sig_infos:signature_infos ->
+ ctxt:Ppxlib.Expansion_context.Extension.t ->
+ Ppxlib.expression ->
+ Ppxlib__.Import.signature_item
PPX intended for use an a Ppxlib extender. The default sig_infos
argument contains descriptions for the standard library under "stdlib"
and for threads/events under "threads"
.
Signature_builder_ppx
Hide_stdlib_variants.Stdlib_alerts
Hide_stdlib_variants.Stdlib_components
Hide_stdlib_variants.Stdlib_variants
Hide_stdlib_variants.Threads_alerts
Std_overrides.Hide_stdlib_variants
Prevent access to the full variant library. Intended to be opened at the top level to hide the Stdlib_variants
module, and a couple others.
This is included in the other overrides modules, so you usually don't need to pass it to the -open
flag yourself. However, you should use it if you define your own override module based on less-power stdlib variants.
These modules are intentionally empty.
module Stdlib_variants : sig ... end
module Stdlib_components : sig ... end
module Stdlib_alerts : sig ... end
module Threads_alerts : sig ... end
Std_overrides.Stdlib_alerting
Puts an alerting Stdlib
into scope, from Stdlib_alerts.Stdlib_alerting
.
module Stdlib = Stdlib_alerts.Stdlib_alerting
include module type of struct include Stdlib_alerts.Stdlib_alerting end
Stdlib
, but with the above module type.
raise
primitives and standard exceptionsinclude sig ... end
The Exit
exception is not raised by any library function. It is provided for use in your programs.
Exception raised when none of the cases of a pattern-matching apply. The arguments are the location of the match keyword in the source code (file name, line number, column number).
Exception raised when an assertion fails. The arguments are the location of the assert keyword in the source code (file name, line number, column number).
Exception raised by library functions to signal that the given arguments do not make sense. The string gives some information to the programmer. As a general rule, this exception should not be caught, it denotes a programming error and the code should be modified not to trigger it.
Exception raised by library functions to signal that they are undefined on the given arguments. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Failure _ instead).
Exception raised by the garbage collector when there is insufficient memory to complete the computation. (Not reliable for allocations on the minor heap.)
Exception raised by the bytecode interpreter when the evaluation stack reaches its maximal size. This often indicates infinite or excessively deep recursion in the user's program.
Before 4.10, it was not fully implemented by the native-code compiler.
Exception raised by the input/output functions to report an operating system error. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Sys_error _ instead).
Exception raised by input functions to signal that the end of file has been reached.
Exception raised by integer division and remainder operations when their second argument is zero.
A special case of Sys_error raised when no I/O is possible on a non-blocking I/O channel.
Not including the impure (==)
and (!=)
.
include sig ... end
e1 = e2
tests for structural equality of e1
and e2
. Mutable structures (e.g. references and arrays) are equal if and only if their current contents are structurally equal, even if the two mutable objects are not the same physical object. Equality between functional values raises Invalid_argument
. Equality between cyclic data structures may not terminate. Left-associative operator, see Ocaml_operators
for more information.
Negation of Stdlib.(=)
. Left-associative operator, see Ocaml_operators
for more information.
See Stdlib.(>=)
. Left-associative operator, see Ocaml_operators
for more information.
See Stdlib.(>=)
. Left-associative operator, see Ocaml_operators
for more information.
See Stdlib.(>=)
. Left-associative operator, see Ocaml_operators
for more information.
Structural ordering functions. These functions coincide with the usual orderings over integers, characters, strings, byte sequences and floating-point numbers, and extend them to a total ordering over all types. The ordering is compatible with ( = )
. As in the case of ( = )
, mutable structures are compared by contents. Comparison between functional values raises Invalid_argument
. Comparison between cyclic structures may not terminate. Left-associative operator, see Ocaml_operators
for more information.
compare x y
returns 0
if x
is equal to y
, a negative integer if x
is less than y
, and a positive integer if x
is greater than y
. The ordering implemented by compare
is compatible with the comparison predicates =
, <
and >
defined above, with one difference on the treatment of the float value Stdlib.nan
. Namely, the comparison predicates treat nan
as different from any other float value, including itself; while compare
treats nan
as equal to itself and less than any other float value. This treatment of nan
ensures that compare
defines a total ordering relation.
compare
applied to functional values may raise Invalid_argument
. compare
applied to cyclic structures may not terminate.
The compare
function can be used as the comparison function required by the Set.Make
and Map.Make
functors, as well as the List.sort
and Array.sort
functions.
Return the smaller of the two arguments. The result is unspecified if one of the arguments contains the float value nan
.
The impure (==)
and (!=)
include sig ... end
e1 == e2
tests for physical equality of e1
and e2
. On mutable types such as references, arrays, byte sequences, records with mutable fields and objects with mutable instance variables, e1 == e2
is true if and only if physical modification of e1
also affects e2
. On non-mutable types, the behavior of ( == )
is implementation-dependent; however, it is guaranteed that e1 == e2
implies compare e1 e2 = 0
. Left-associative operator, see Ocaml_operators
for more information.
Negation of Stdlib.(==)
. Left-associative operator, see Ocaml_operators
for more information.
include sig ... end
The boolean 'and'. Evaluation is sequential, left-to-right: in e1 && e2
, e1
is evaluated first, and if it returns false
, e2
is not evaluated at all. Right-associative operator, see Ocaml_operators
for more information.
These are safe in the sense that referential transparency is preserved, if two uses of a macro at separate locations are considered separate occurrences.
include sig ... end
__LOC__
returns the location at which this expression appears in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d".
__LINE__
returns the line number at which this expression appears in the file currently being parsed by the compiler.
__POS__
returns a tuple (file,lnum,cnum,enum)
, corresponding to the location at which this expression appears in the file currently being parsed by the compiler. file
is the current filename, lnum
the line number, cnum
the character position in the line and enum
the last character position in the line.
__FUNCTION__
returns the name of the current function or method, including any enclosing modules or classes.
__LOC_OF__ expr
returns a pair (loc, expr)
where loc
is the location of expr
in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d".
__LINE_OF__ expr
returns a pair (line, expr)
, where line
is the line number at which the expression expr
appears in the file currently being parsed by the compiler.
__POS_OF__ expr
returns a pair (loc,expr)
, where loc
is a tuple (file,lnum,cnum,enum)
corresponding to the location at which the expression expr
appears in the file currently being parsed by the compiler. file
is the current filename, lnum
the line number, cnum
the character position in the line and enum
the last character position in the line.
include sig ... end
Reverse-application operator: x |> f |> g
is exactly equivalent to g (f (x))
. Left-associative operator, see Ocaml_operators
for more information.
include sig ... end
Unary negation. You can also write - e
instead of ~- e
. Unary operator, see Ocaml_operators
for more information.
Unary addition. You can also write + e
instead of ~+ e
. Unary operator, see Ocaml_operators
for more information.
Integer addition. Left-associative operator, see Ocaml_operators
for more information.
Integer subtraction. Left-associative operator, , see Ocaml_operators
for more information.
Integer multiplication. Left-associative operator, see Ocaml_operators
for more information.
Integer division. Integer division rounds the real quotient of its arguments towards zero. More precisely, if x >= 0
and y > 0
, x / y
is the greatest integer less than or equal to the real quotient of x
by y
. Moreover, (- x) / y = x / (- y) = - (x / y)
. Left-associative operator, see Ocaml_operators
for more information.
Integer remainder. If y
is not zero, the result of x mod y
satisfies the following properties: x = (x / y) * y + x mod y
and abs(x mod y) <= abs(y) - 1
. If y = 0
, x mod y
raises Division_by_zero
. Note that x mod y
is negative only if x < 0
. Left-associative operator, see Ocaml_operators
for more information.
abs x
is the absolute value of x
. On min_int
this is min_int
itself and thus remains negative.
Bitwise logical and. Left-associative operator, see Ocaml_operators
for more information.
Bitwise logical or. Left-associative operator, see Ocaml_operators
for more information.
Bitwise logical exclusive or. Left-associative operator, see Ocaml_operators
for more information.
n lsl m
shifts n
to the left by m
bits. The result is unspecified if m < 0
or m > Sys.int_size
. Right-associative operator, see Ocaml_operators
for more information.
n lsr m
shifts n
to the right by m
bits. This is a logical shift: zeroes are inserted regardless of the sign of n
. The result is unspecified if m < 0
or m > Sys.int_size
. Right-associative operator, see Ocaml_operators
for more information.
n asr m
shifts n
to the right by m
bits. This is an arithmetic shift: the sign bit of n
is replicated. The result is unspecified if m < 0
or m > Sys.int_size
. Right-associative operator, see Ocaml_operators
for more information.
include sig ... end
Unary negation. You can also write -. e
instead of ~-. e
. Unary operator, see Ocaml_operators
for more information.
Unary addition. You can also write +. e
instead of ~+. e
. Unary operator, see Ocaml_operators
for more information.
Floating-point addition. Left-associative operator, see Ocaml_operators
for more information.
Floating-point subtraction. Left-associative operator, see Ocaml_operators
for more information.
Floating-point multiplication. Left-associative operator, see Ocaml_operators
for more information.
Floating-point division. Left-associative operator, see Ocaml_operators
for more information.
Exponentiation. Right-associative operator, see Ocaml_operators
for more information.
expm1 x
computes exp x -. 1.0
, giving numerically-accurate results even if x
is close to 0.0
.
Arc cosine. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and is between 0.0
and pi
.
Arc sine. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and is between -pi/2
and pi/2
.
atan2 y x
returns the arc tangent of y /. x
. The signs of x
and y
are used to determine the quadrant of the result. Result is in radians and is between -pi
and pi
.
hypot x y
returns sqrt(x *. x + y *. y)
, that is, the length of the hypotenuse of a right-angled triangle with sides of length x
and y
, or, equivalently, the distance of the point (x,y)
to origin. If one of x
or y
is infinite, returns infinity
even if the other is nan
.
Hyperbolic arc cosine. The argument must fall within the range [1.0, inf]
. Result is in radians and is between 0.0
and inf
.
log1p x
computes log(1.0 +. x)
(natural logarithm), giving numerically-accurate results even if x
is close to 0.0
.
Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians.
Hyperbolic arc tangent. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and ranges over the entire real line.
Round above to an integer value. ceil f
returns the least integer value greater than or equal to f
. The result is returned as a float.
Round below to an integer value. floor f
returns the greatest integer value less than or equal to f
. The result is returned as a float.
copysign x y
returns a float whose absolute value is that of x
and whose sign is that of y
. If x
is nan
, returns nan
. If y
is nan
, returns either x
or -. x
, but it is not specified which.
mod_float a b
returns the remainder of a
with respect to b
. The returned value is a -. n *. b
, where n
is the quotient a /. b
rounded towards zero to an integer.
frexp f
returns the pair of the significant and the exponent of f
. When f
is zero, the significant x
and the exponent n
of f
are equal to zero. When f
is non-zero, they are defined by f = x *. 2 ** n
and 0.5 <= x < 1.0
.
Same as Stdlib.float_of_int
.
Same as Stdlib.int_of_float
.
Truncate the given floating-point number to an integer. The result is unspecified if the argument is nan
or falls outside the range of representable integers.
A special floating-point value denoting the result of an undefined operation such as 0.0 /. 0.0
. Stands for 'not a number'. Any floating-point operation with nan
as argument returns nan
as result, unless otherwise specified in IEEE 754 standard. As for floating-point comparisons, =
, <
, <=
, >
and >=
return false
and <>
returns true
if one or both of their arguments is nan
.
nan
is a quiet NaN since 5.1; it was a signaling NaN before.
The difference between 1.0
and the smallest exactly representable floating-point number greater than 1.0
.
type fpclass = Stdlib_alerts.Stdlib_alerting.fpclass =
The five classes of floating-point numbers, as determined by the Stdlib.classify_float
function.
val classify_float : float -> fpclass
Return the class of the given floating-point number: normal, subnormal, zero, infinite, or not a number.
More in Stdlib.String
More in Stdlib.Char
include sig ... end
include sig ... end
Return the string representation of a boolean. As the returned values may be shared, the user should not modify them directly.
Convert the given string to a boolean.
Return None
if the string is not "true"
or "false"
.
Same as Stdlib.bool_of_string_opt
, but raise Invalid_argument "bool_of_string"
instead of returning None
.
Convert the given string to an integer. The string is read in decimal (by default, or if the string begins with 0u
), in hexadecimal (if it begins with 0x
or 0X
), in octal (if it begins with 0o
or 0O
), or in binary (if it begins with 0b
or 0B
).
The 0u
prefix reads the input as an unsigned integer in the range [0, 2*max_int+1]
. If the input exceeds max_int
it is converted to the signed integer min_int + input - max_int - 1
.
The _
(underscore) character can appear anywhere in the string and is ignored.
Return None
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 int
.
Same as Stdlib.int_of_string_opt
, but raise Failure "int_of_string"
instead of returning None
.
Return a string representation of a floating-point number.
This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see Printf
.
Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by 0x
or 0X
).
The format of decimal floating-point numbers is [-] dd.ddd (e|E) [+|-] dd
, where d
stands for a decimal digit.
The format of hexadecimal floating-point numbers is [-] 0(x|X) hh.hhh (p|P) [+|-] dd
, where h
stands for an hexadecimal digit and d
for a decimal digit.
In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional.
The _
(underscore) character can appear anywhere in the string and is ignored.
Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon.
Return None
if the given string is not a valid representation of a float.
Same as Stdlib.float_of_string_opt
, but raise Failure "float_of_string"
instead of returning None
.
More in Stdlib.List
include sig ... end
l0 @ l1
appends l1
to l0
. Same function as List.append
. Right-associative operator, see Ocaml_operators
for more information.
This is regular, unmocked, IO.
include sig ... end
type in_channel = Stdlib_alerts.Stdlib_alerting.in_channel
The type of input channel.
type out_channel = Stdlib_alerts.Stdlib_alerting.out_channel
The type of output channel.
val stdin : in_channel
The standard input for the process.
val stdout : out_channel
The standard output for the process.
val stderr : out_channel
The standard error output for the process.
Print a floating-point number, in decimal, on standard output.
The conversion of the number to a string uses string_of_float
and can involve a loss of precision.
Print a string, followed by a newline character, on standard output and flush standard output.
Print a newline character on standard output, and flush standard output. This can be used to simulate line buffering of standard output.
Print a floating-point number, in decimal, on standard error.
The conversion of the number to a string uses string_of_float
and can involve a loss of precision.
Print a string, followed by a newline character on standard error and flush standard error.
Print a newline character on standard error, and flush standard error.
Flush standard output, then read characters from standard input until a newline character is encountered.
Return the string of all characters read, without the newline character at the end.
Flush standard output, then read one line from standard input and convert it to an integer.
Return None
if the line read is not a valid representation of an integer.
Same as Stdlib.read_int_opt
, but raise Failure "int_of_string"
instead of returning None
.
Flush standard output, then read one line from standard input and convert it to a floating-point number.
Return None
if the line read is not a valid representation of a floating-point number.
Same as Stdlib.read_float_opt
, but raise Failure "float_of_string"
instead of returning None
.
type open_flag = Stdlib_alerts.Stdlib_alerting.open_flag =
| Open_rdonly
open for reading.
*)| Open_wronly
open for writing.
*)| Open_append
open for appending: always write at end of file.
*)| Open_creat
create the file if it does not exist.
*)| Open_trunc
empty the file if it already exists.
*)| Open_excl
fail if Open_creat and the file already exists.
*)| Open_binary
open in binary mode (no conversion).
*)| Open_text
open in text mode (may perform conversions).
*)| Open_nonblock
open in non-blocking mode.
*)Opening modes for Stdlib.open_out_gen
and Stdlib.open_in_gen
.
val open_out : string -> out_channel
Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists.
val open_out_bin : string -> out_channel
Same as Stdlib.open_out
, but the file is opened in binary mode, so that no translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like Stdlib.open_out
.
val open_out_gen : open_flag list -> int -> string -> out_channel
open_out_gen mode perm filename
opens the named file for writing, as described above. The extra argument mode
specifies the opening mode. The extra argument perm
specifies the file permissions, in case the file must be created. Stdlib.open_out
and Stdlib.open_out_bin
are special cases of this function.
val flush : out_channel -> unit
Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time.
val output_char : out_channel -> char -> unit
Write the character on the given output channel.
val output_string : out_channel -> string -> unit
Write the string on the given output channel.
val output_bytes : out_channel -> bytes -> unit
Write the byte sequence on the given output channel.
val output : out_channel -> bytes -> int -> int -> unit
output oc buf pos len
writes len
characters from byte sequence buf
, starting at offset pos
, to the given output channel oc
.
val output_substring : out_channel -> string -> int -> int -> unit
Same as output
but take a string as argument instead of a byte sequence.
val output_byte : out_channel -> int -> unit
Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256.
val output_binary_int : out_channel -> int -> unit
Write one integer in binary format (4 bytes, big-endian) on the given output channel. The given integer is taken modulo 232. The only reliable way to read it back is through the Stdlib.input_binary_int
function. The format is compatible across all machines for a given version of OCaml.
val output_value : out_channel -> 'a -> unit
Write the representation of a structured value of any type to a channel. Circularities and sharing inside the value are detected and preserved. The object can be read back, by the function Stdlib.input_value
. See the description of module Marshal
for more information. Stdlib.output_value
is equivalent to Marshal.to_channel
with an empty list of flags.
val seek_out : out_channel -> int -> unit
seek_out chan pos
sets the current writing position to pos
for channel chan
. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified.
val pos_out : out_channel -> int
Return the current writing position for the given channel. Does not work on channels opened with the Open_append
flag (returns unspecified results). For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with pos_out
, then going back to this position using seek_out
will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode.
val out_channel_length : out_channel -> int
Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless.
val close_out : out_channel -> unit
Close the given channel, flushing all buffered write operations. Output functions raise a Sys_error
exception when they are applied to a closed output channel, except close_out
and flush
, which do nothing when applied to an already closed channel. Note that close_out
may raise Sys_error
if the operating system signals an error when flushing or closing.
val close_out_noerr : out_channel -> unit
Same as close_out
, but ignore all errors.
val set_binary_mode_out : out_channel -> bool -> unit
set_binary_mode_out oc true
sets the channel oc
to binary mode: no translations take place during output. set_binary_mode_out oc false
sets the channel oc
to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from \n
to \r\n
. This function has no effect under operating systems that do not distinguish between text mode and binary mode.
val open_in : string -> in_channel
Open the named file for reading, and return a new input channel on that file, positioned at the beginning of the file.
val open_in_bin : string -> in_channel
Same as Stdlib.open_in
, but the file is opened in binary mode, so that no translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like Stdlib.open_in
.
val open_in_gen : open_flag list -> int -> string -> in_channel
open_in_gen mode perm filename
opens the named file for reading, as described above. The extra arguments mode
and perm
specify the opening mode and file permissions. Stdlib.open_in
and Stdlib.open_in_bin
are special cases of this function.
val input_char : in_channel -> char
Read one character from the given input channel.
val input_line : in_channel -> string
Read characters from the given input channel, until a newline character is encountered. Return the string of all characters read, without the newline character at the end.
val input : in_channel -> bytes -> int -> int -> int
input ic buf pos len
reads up to len
characters from the given channel ic
, storing them in byte sequence buf
, starting at character number pos
. It returns the actual number of characters read, between 0 and len
(inclusive). A return value of 0 means that the end of file was reached. A return value between 0 and len
exclusive means that not all requested len
characters were read, either because no more characters were available at that time, or because the implementation found it convenient to do a partial read; input
must be called again to read the remaining characters, if desired. (See also Stdlib.really_input
for reading exactly len
characters.) Exception Invalid_argument "input"
is raised if pos
and len
do not designate a valid range of buf
.
val really_input : in_channel -> bytes -> int -> int -> unit
really_input ic buf pos len
reads len
characters from channel ic
, storing them in byte sequence buf
, starting at character number pos
.
val really_input_string : in_channel -> int -> string
really_input_string ic len
reads len
characters from channel ic
and returns them in a new string.
val input_byte : in_channel -> int
Same as Stdlib.input_char
, but return the 8-bit integer representing the character.
val input_binary_int : in_channel -> int
Read an integer encoded in binary format (4 bytes, big-endian) from the given input channel. See Stdlib.output_binary_int
.
val input_value : in_channel -> 'a
Read the representation of a structured value, as produced by Stdlib.output_value
, and return the corresponding value. This function is identical to Marshal.from_channel
; see the description of module Marshal
for more information, in particular concerning the lack of type safety.
val seek_in : in_channel -> int -> unit
seek_in chan pos
sets the current reading position to pos
for channel chan
. This works only for regular files. On files of other kinds, the behavior is unspecified.
val pos_in : in_channel -> int
Return the current reading position for the given channel. For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with pos_in
, then going back to this position using seek_in
will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode.
val in_channel_length : in_channel -> int
Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode.
val close_in : in_channel -> unit
Close the given channel. Input functions raise a Sys_error
exception when they are applied to a closed input channel, except close_in
, which does nothing when applied to an already closed channel.
val close_in_noerr : in_channel -> unit
Same as close_in
, but ignore all errors.
val set_binary_mode_in : in_channel -> bool -> unit
set_binary_mode_in ic true
sets the channel ic
to binary mode: no translations take place during input. set_binary_mode_out ic false
sets the channel ic
to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from \r\n
to \n
. This function has no effect under operating systems that do not distinguish between text mode and binary mode.
module LargeFile = Stdlib_alerts.Stdlib_alerting.LargeFile
Operations on large files. This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type int64
) instead of regular integers (type int
), these alternate functions allow operating on files whose sizes are greater than max_int
.
include sig ... end
The type of references (mutable indirection cells) containing a value of type 'a
.
val ref : 'a -> 'a ref
Return a fresh reference containing the given value.
val (!) : 'a ref -> 'a
!r
returns the current contents of reference r
. Equivalent to fun r -> r.contents
. Unary operator, see Ocaml_operators
for more information.
val (:=) : 'a ref -> 'a -> unit
r := a
stores the value of a
in reference r
. Equivalent to fun r v -> r.contents <- v
. Right-associative operator, see Ocaml_operators
for more information.
val incr : int ref -> unit
Increment the integer contained in the given reference. Equivalent to fun r -> r := succ !r
.
val decr : int ref -> unit
Decrement the integer contained in the given reference. Equivalent to fun r -> r := pred !r
.
More in Stdlib.Result
include sig ... end
More in Stdlib.Scanf
, Stdlib.Printf
, and Stdlib.Format
include sig ... end
type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6
type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4
format_of_string s
returns a format string read from the string literal s
. Note: format_of_string
can not convert a string argument that is not a literal. If you need this functionality, use the more general Scanf.format_from_string
function.
val (^^) :
+ ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
+ ('f, 'b, 'c, 'e, 'g, 'h) format6 ->
+ ('a, 'b, 'c, 'd, 'g, 'h) format6
f1 ^^ f2
catenates format strings f1
and f2
. The result is a format string that behaves as the concatenation of format strings f1
and f2
: in case of formatted output, it accepts arguments from f1
, then arguments from f2
; in case of formatted input, it returns results from f1
, then results from f2
. Right-associative operator, see Ocaml_operators
for more information.
include sig ... end
Terminate the process, returning the given status code to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. All open output channels are flushed with flush_all
. The callbacks registered with Domain.at_exit
are called followed by those registered with Stdlib.at_exit
.
An implicit exit 0
is performed each time a program terminates normally. An implicit exit 2
is performed if the program terminates early because of an uncaught exception.
Register the given function to be called at program termination time. The functions registered with at_exit
will be called when the program does any of the following:
Stdlib.exit
caml_shutdown
. The functions are called in 'last in, first out' order: the function most recently added with at_exit
is called first.include sig ... end
module Bool = Stdlib_alerts.Stdlib_alerting.Bool
module Complex = Stdlib_alerts.Stdlib_alerting.Complex
module Either = Stdlib_alerts.Stdlib_alerting.Either
module Fun = Stdlib_alerts.Stdlib_alerting.Fun
module Int = Stdlib_alerts.Stdlib_alerting.Int
module Int32 = Stdlib_alerts.Stdlib_alerting.Int32
module Int64 = Stdlib_alerts.Stdlib_alerting.Int64
module Lazy = Stdlib_alerts.Stdlib_alerting.Lazy
module Map = Stdlib_alerts.Stdlib_alerting.Map
module Nativeint = Stdlib_alerts.Stdlib_alerting.Nativeint
module Option = Stdlib_alerts.Stdlib_alerting.Option
module Result = Stdlib_alerts.Stdlib_alerting.Result
module Set = Stdlib_alerts.Stdlib_alerting.Set
module Unit = Stdlib_alerts.Stdlib_alerting.Unit
module Char = Stdlib_alerts.Stdlib_alerting.Char
module Digest = Stdlib_alerts.Stdlib_alerting.Digest
module Filename = Stdlib_alerts.Stdlib_alerting.Filename
module Float = Stdlib_alerts.Stdlib_alerting.Float
module Hashtbl = Stdlib_alerts.Stdlib_alerting.Hashtbl
module List = Stdlib_alerts.Stdlib_alerting.List
module ListLabels = Stdlib_alerts.Stdlib_alerting.ListLabels
module MoreLabels = Stdlib_alerts.Stdlib_alerting.MoreLabels
module Printexc = Stdlib_alerts.Stdlib_alerting.Printexc
module Printf = Stdlib_alerts.Stdlib_alerting.Printf
module Scanf = Stdlib_alerts.Stdlib_alerting.Scanf
module Seq = Stdlib_alerts.Stdlib_alerting.Seq
module StdLabels = Stdlib_alerts.Stdlib_alerting.StdLabels
module String = Stdlib_alerts.Stdlib_alerting.String
module StringLabels = Stdlib_alerts.Stdlib_alerting.StringLabels
module Uchar = Stdlib_alerts.Stdlib_alerting.Uchar
include sig ... end
module Array = Stdlib_alerts.Stdlib_alerting.Array
module ArrayLabels = Stdlib_alerts.Stdlib_alerting.ArrayLabels
module Bigarray = Stdlib_alerts.Stdlib_alerting.Bigarray
include sig ... end
module Buffer = Stdlib_alerts.Stdlib_alerting.Buffer
module Bytes = Stdlib_alerts.Stdlib_alerting.Bytes
module BytesLabels = Stdlib_alerts.Stdlib_alerting.BytesLabels
module Format = Stdlib_alerts.Stdlib_alerting.Format
module Lexing = Stdlib_alerts.Stdlib_alerting.Lexing
module Parsing = Stdlib_alerts.Stdlib_alerting.Parsing
module Queue = Stdlib_alerts.Stdlib_alerting.Queue
module Random = Stdlib_alerts.Stdlib_alerting.Random
module Stack = Stdlib_alerts.Stdlib_alerting.Stack
include sig ... end
module In_channel = Stdlib_alerts.Stdlib_alerting.In_channel
module Out_channel = Stdlib_alerts.Stdlib_alerting.Out_channel
Modules containing advanced features for interacting with the runtime system.
include sig ... end
module Arg = Stdlib_alerts.Stdlib_alerting.Arg
module Atomic = Stdlib_alerts.Stdlib_alerting.Atomic
module Callback = Stdlib_alerts.Stdlib_alerting.Callback
module Condition = Stdlib_alerts.Stdlib_alerting.Condition
module Domain = Stdlib_alerts.Stdlib_alerting.Domain
module Effect = Stdlib_alerts.Stdlib_alerting.Effect
module Ephemeron = Stdlib_alerts.Stdlib_alerting.Ephemeron
module Gc = Stdlib_alerts.Stdlib_alerting.Gc
module Marshal = Stdlib_alerts.Stdlib_alerting.Marshal
module Mutex = Stdlib_alerts.Stdlib_alerting.Mutex
module Obj = Stdlib_alerts.Stdlib_alerting.Obj
module Oo = Stdlib_alerts.Stdlib_alerting.Oo
module Sys = Stdlib_alerts.Stdlib_alerting.Sys
module Weak = Stdlib_alerts.Stdlib_alerting.Weak
include module type of struct include Hide_stdlib_variants end
These modules are intentionally empty.
module Stdlib_variants = Hide_stdlib_variants.Stdlib_variants
module Stdlib_components = Hide_stdlib_variants.Stdlib_components
module Stdlib_alerts = Hide_stdlib_variants.Stdlib_alerts
module Threads_alerts = Hide_stdlib_variants.Threads_alerts
Std_overrides.Stdlib_safe
Puts the safe parts of Stdlib
into scope, from Stdlib_components.Stdlib_safe
module Stdlib = Stdlib_components.Stdlib_safe
include module type of struct include Stdlib_components.Stdlib_safe end
include module type of struct include Stdlib_components.Exceptions end
include module type of struct include Stdlib_components.Composition end
include module type of struct include Stdlib_components.Debugging end
include module type of struct include Stdlib_components.Comparisons end
include module type of struct include Stdlib_components.BooleanOperations end
include module type of struct include Stdlib_components.IntegerOperations end
include module type of struct include Stdlib_components.FloatingPointOperations end
val classify_float : float -> fpclass
include module type of struct include Stdlib_components.StringOperations end
include module type of struct include Stdlib_components.CharOperations end
include module type of struct include Stdlib_components.UnitOperations end
include module type of struct include Stdlib_components.PairOperations end
include module type of struct include Stdlib_components.Result end
include module type of struct include Stdlib_components.StringConversion end
include module type of struct include Stdlib_components.ListOperations end
include module type of struct include Stdlib_components.Formats end
include module type of struct include Stdlib_components.SafeAliases end
module Bool = Stdlib_components.Stdlib_safe.Bool
module Char = Stdlib_components.Stdlib_safe.Char
module Complex = Stdlib_components.Stdlib_safe.Complex
module Either = Stdlib_components.Stdlib_safe.Either
module Float = Stdlib_components.Stdlib_safe.Float
module Fun = Stdlib_components.Stdlib_safe.Fun
module Int = Stdlib_components.Stdlib_safe.Int
module Int32 = Stdlib_components.Stdlib_safe.Int32
module Int64 = Stdlib_components.Stdlib_safe.Int64
module Lazy = Stdlib_components.Stdlib_safe.Lazy
module List = Stdlib_components.Stdlib_safe.List
module ListLabels = Stdlib_components.Stdlib_safe.ListLabels
module Map = Stdlib_components.Stdlib_safe.Map
module MoreLabels = Stdlib_components.Stdlib_safe.MoreLabels
module Nativeint = Stdlib_components.Stdlib_safe.Nativeint
module Option = Stdlib_components.Stdlib_safe.Option
module Printexc = Stdlib_components.Stdlib_safe.Printexc
module Printf = Stdlib_components.Stdlib_safe.Printf
module Result = Stdlib_components.Stdlib_safe.Result
module Scanf = Stdlib_components.Stdlib_safe.Scanf
module Seq = Stdlib_components.Stdlib_safe.Seq
module Set = Stdlib_components.Stdlib_safe.Set
module StdLabels = Stdlib_components.Stdlib_safe.StdLabels
module String = Stdlib_components.Stdlib_safe.String
module StringLabels = Stdlib_components.Stdlib_safe.StringLabels
module Uchar = Stdlib_components.Stdlib_safe.Uchar
module Unit = Stdlib_components.Stdlib_safe.Unit
include module type of struct include Hide_stdlib_variants end
These modules are intentionally empty.
module Stdlib_variants = Hide_stdlib_variants.Stdlib_variants
module Stdlib_components = Hide_stdlib_variants.Stdlib_components
module Stdlib_alerts = Hide_stdlib_variants.Stdlib_alerts
module Threads_alerts = Hide_stdlib_variants.Threads_alerts
Std_overrides
Ready-to-use modules for replacing the default pervasives, using -open
.
module Hide_stdlib_variants : sig ... end
Prevent access to the full variant library. Intended to be opened at the top level to hide the Stdlib_variants
module, and a couple others.
module Stdlib_safe : sig ... end
Puts the safe parts of Stdlib
into scope, from Stdlib_components.Stdlib_safe
module Stdlib_alerting : sig ... end
Puts an alerting Stdlib
into scope, from Stdlib_alerts.Stdlib_alerting
.
Stdlib_alerting.Char
include sig ... end
Return a string representing the given character, with special characters escaped following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash, double-quote, and single-quote.
Convert the given character to its equivalent lowercase character, using the US-ASCII character set.
Convert the given character to its equivalent uppercase character, using the US-ASCII character set.
The 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 seeded_hash : int -> t -> int
A seeded hash function for characters, with the same output value as Hashtbl.seeded_hash
. This function allows this module to be passed as argument to the functor Hashtbl.MakeSeeded
.
val hash : t -> int
An unseeded hash function for characters, with the same output value as Hashtbl.hash
. This function allows this module to be passed as argument to the functor Hashtbl.Make
.
Stdlib_alerting.Digest
include sig ... end
The comparison function for 16-character digest, with the same specification as Stdlib.compare
and the implementation shared with String.compare
. Along with the type t
, this function compare
allows the module Digest
to be passed as argument to the functors Set.Make
and Map.Make
.
val string : string -> t
Return the digest of the given string.
val substring : string -> int -> int -> t
Digest.substring s ofs len
returns the digest of the substring of s
starting at index ofs
and containing len
characters.
val to_hex : t -> string
Return the printable hexadecimal representation of the given digest.
val from_hex : string -> t
Convert a hexadecimal representation back into the corresponding digest.
val bytes : bytes -> t
Return the digest of the given byte sequence.
val subbytes : bytes -> int -> int -> t
Digest.subbytes s ofs len
returns the digest of the subsequence of s
starting at index ofs
and containing len
bytes.
val channel : Stdlib.in_channel -> int -> t
If len
is nonnegative, Digest.channel ic len
reads len
characters from channel ic
and returns their digest, or raises End_of_file
if end-of-file is reached before len
characters are read. If len
is negative, Digest.channel ic len
reads all characters from ic
until end-of-file is reached and return their digest.
val file : string -> t
Return the digest of the file whose name is given.
val output : Stdlib.out_channel -> t -> unit
Write a digest on the given output channel.
val input : Stdlib.in_channel -> t
Read a digest from the given input channel.
Stdlib_alerting.Filename
include sig ... end
The conventional name for the parent of the current directory (e.g. ..
in Unix).
concat dir file
returns a file name that designates file file
in directory dir
.
Return true
if the file name is relative to the current directory, false
if it is absolute (i.e. in Unix, starts with /
).
Return true
if the file name is relative and does not start with an explicit reference to the current directory (./
or ../
in Unix), false
if it starts with an explicit reference to the root directory or the current directory.
check_suffix name suff
returns true
if the filename name
ends with the suffix suff
.
Under Windows ports (including Cygwin), comparison is case-insensitive, relying on String.lowercase_ascii
. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows.
chop_suffix name suff
removes the suffix suff
from the filename name
.
chop_suffix_opt ~suffix filename
removes the suffix from the filename
if possible, or returns None
if the filename does not end with the suffix.
Under Windows ports (including Cygwin), comparison is case-insensitive, relying on String.lowercase_ascii
. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows.
extension name
is the shortest suffix ext
of name0
where:
name0
is the longest suffix of name
that does not contain a directory separator;ext
starts with a period;ext
is preceded by at least one non-period character in name0
.If such a suffix does not exist, extension name
is the empty string.
Return the given file name without its extension, as defined in Filename.extension
. If the extension is empty, the function returns the given file name.
The following invariant holds for any file name s
:
remove_extension s ^ extension s = s
Same as Filename.remove_extension
, but raise Invalid_argument
if the given name has an empty extension.
Split a file name into directory name / base file name. If name
is a valid file name, then concat (dirname name) (basename name)
returns a file name which is equivalent to name
. Moreover, after setting the current directory to dirname name
(with Sys.chdir
), references to basename name
(which is a relative file name) designate the same file as name
before the call to Sys.chdir
.
This function conforms to the specification of POSIX.1-2008 for the basename
utility.
See Filename.basename
. This function conforms to the specification of POSIX.1-2008 for the dirname
utility.
null
is "/dev/null"
on POSIX and "NUL"
on Windows. It represents a file on the OS that discards all writes and returns end of file on reads.
Return a quoted version of a file name, suitable for use as one argument in a command line, escaping all meta-characters. Warning: under Windows, the output is only suitable for use with programs that follow the standard Windows quoting conventions.
val quote_command :
+ string ->
+ ?stdin:string ->
+ ?stdout:string ->
+ ?stderr:string ->
+ string list ->
+ string
quote_command cmd args
returns a quoted command line, suitable for use as an argument to Sys.command
, Unix.system
, and the Unix.open_process
functions.
The string cmd
is the command to call. The list args
is the list of arguments to pass to this command. It can be empty.
The optional arguments ?stdin
and ?stdout
and ?stderr
are file names used to redirect the standard input, the standard output, or the standard error of the command. If ~stdin:f
is given, a redirection < f
is performed and the standard input of the command reads from file f
. If ~stdout:f
is given, a redirection > f
is performed and the standard output of the command is written to file f
. If ~stderr:f
is given, a redirection 2> f
is performed and the standard error of the command is written to file f
. If both ~stdout:f
and ~stderr:f
are given, with the exact same file name f
, a 2>&1
redirection is performed so that the standard output and the standard error of the command are interleaved and redirected to the same file f
.
Under Unix and Cygwin, the command, the arguments, and the redirections if any are quoted using Filename.quote
, then concatenated. Under Win32, additional quoting is performed as required by the cmd.exe
shell that is called by Sys.command
.
temp_file prefix suffix
returns the name of a fresh temporary file in the temporary directory. The base name of the temporary file is formed by concatenating prefix
, then a suitably chosen integer number, then suffix
. The optional argument temp_dir
indicates the temporary directory to use, defaulting to the current result of Filename.get_temp_dir_name
. The temporary file is created empty, with permissions 0o600
(readable and writable only by the file owner). The file is guaranteed to be different from any other file that existed when temp_file
was called.
val open_temp_file :
+ ?mode:Stdlib.open_flag list ->
+ ?perms:int ->
+ ?temp_dir:string ->
+ string ->
+ string ->
+ string * Stdlib.out_channel
Same as Filename.temp_file
, but returns both the name of a fresh temporary file, and an output channel opened (atomically) on this file. This function is more secure than temp_file
: there is no risk that the temporary file will be modified (e.g. replaced by a symbolic link) before the program opens it. The optional argument mode
is a list of additional flags to control the opening of the file. It can contain one or several of Open_append
, Open_binary
, and Open_text
. The default is [Open_text]
(open in text mode). The file is created with permissions perms
(defaults to readable and writable only by the file owner, 0o600
).
temp_dir prefix suffix
creates and returns the name of a fresh temporary directory with permissions perms
(defaults to 0o700) inside temp_dir
. The base name of the temporary directory is formed by concatenating prefix
, then a suitably chosen integer number, then suffix
. The optional argument temp_dir
indicates the temporary directory to use, defaulting to the current result of Filename.get_temp_dir_name
. The temporary directory is created empty, with permissions 0o700
(readable, writable, and searchable only by the file owner). The directory is guaranteed to be different from any other directory that existed when temp_dir
was called.
If temp_dir does not exist, this function does not create it. Instead, it raises Sys_error.
The name of the temporary directory: Under Unix, the value of the TMPDIR
environment variable, or "/tmp" if the variable is not set. Under Windows, the value of the TEMP
environment variable, or "." if the variable is not set. The temporary directory can be changed with Filename.set_temp_dir_name
.
Change the temporary directory returned by Filename.get_temp_dir_name
and used by Filename.temp_file
and Filename.open_temp_file
. The temporary directory is a domain-local value which is inherited by child domains.
Float.Array
Float arrays with packed representation.
val length : t -> int
Return the length (number of elements) of the given floatarray.
val get : t -> int -> float
get a n
returns the element number n
of floatarray a
.
val set : t -> int -> float -> unit
set a n x
modifies floatarray a
in place, replacing element number n
with x
.
val make : int -> float -> t
make n x
returns a fresh floatarray of length n
, initialized with x
.
val create : int -> t
create n
returns a fresh floatarray of length n
, with uninitialized data.
val init : int -> (int -> float) -> t
init n f
returns a fresh floatarray of length n
, with element number i
initialized to the result of f i
. In other terms, init n f
tabulates the results of f
applied to the integers 0
to n-1
.
append v1 v2
returns a fresh floatarray containing the concatenation of the floatarrays v1
and v2
.
sub a pos len
returns a fresh floatarray of length len
, containing the elements number pos
to pos + len - 1
of floatarray a
.
copy a
returns a copy of a
, that is, a fresh floatarray containing the same elements as a
.
val fill : t -> int -> int -> float -> unit
fill a pos len x
modifies the floatarray a
in place, storing x
in elements number pos
to pos + len - 1
.
blit src src_pos dst dst_pos len
copies len
elements from floatarray src
, starting at element number src_pos
, to floatarray dst
, starting at element number dst_pos
. It works correctly even if src
and dst
are the same floatarray, and the source and destination chunks overlap.
val to_list : t -> float list
to_list a
returns the list of all the elements of a
.
val of_list : float list -> t
of_list l
returns a fresh floatarray containing the elements of l
.
val iter : (float -> unit) -> t -> unit
iter f a
applies function f
in turn to all the elements of a
. It is equivalent to f a.(0); f a.(1); ...; f a.(length a - 1); ()
.
val iteri : (int -> float -> unit) -> t -> unit
Same as iter
, but the function is applied with the index of the element as first argument, and the element itself as second argument.
map f a
applies function f
to all the elements of a
, and builds a floatarray with the results returned by f
.
val map_inplace : (float -> float) -> t -> unit
map_inplace f a
applies function f
to all elements of a
, and updates their values in place.
Same as map
, but the function is applied to the index of the element as first argument, and the element itself as second argument.
val mapi_inplace : (int -> float -> float) -> t -> unit
Same as map_inplace
, but the function is applied to the index of the element as first argument, and the element itself as second argument.
val fold_left : ('acc -> float -> 'acc) -> 'acc -> t -> 'acc
fold_left f x init
computes f (... (f (f x init.(0)) init.(1)) ...) init.(n-1)
, where n
is the length of the floatarray init
.
val fold_right : (float -> 'acc -> 'acc) -> t -> 'acc -> 'acc
fold_right f a init
computes f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))
, where n
is the length of the floatarray a
.
Array.iter2 f a b
applies function f
to all the elements of a
and b
.
map2 f a b
applies function f
to all the elements of a
and b
, and builds a floatarray with the results returned by f
: [| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]
.
val for_all : (float -> bool) -> t -> bool
for_all f [|a1; ...; an|]
checks if all elements of the floatarray satisfy the predicate f
. That is, it returns (f a1) && (f a2) && ... && (f an)
.
val exists : (float -> bool) -> t -> bool
exists f [|a1; ...; an|]
checks if at least one element of the floatarray satisfies the predicate f
. That is, it returns (f a1) || (f a2) || ... || (f an)
.
val mem : float -> t -> bool
mem a set
is true if and only if there is an element of set
that is structurally equal to a
, i.e. there is an x
in set
such that compare a x = 0
.
val mem_ieee : float -> t -> bool
Same as mem
, but uses IEEE equality instead of structural equality.
val find_opt : (float -> bool) -> t -> float option
val find_index : (float -> bool) -> t -> int option
find_index f a
returns Some i
, where i
is the index of the first element of the array a
that satisfies f x
, if there is such an element.
It returns None
if there is no such element.
val find_map : (float -> 'a option) -> t -> 'a option
val find_mapi : (int -> float -> 'a option) -> t -> 'a option
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
val sort : (float -> float -> int) -> t -> unit
Sort a floatarray in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, Stdlib.compare
is a suitable comparison function. After calling sort
, the array is sorted in place in increasing order. sort
is guaranteed to run in constant heap space and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant stack space.
Specification of the comparison function: Let a
be the floatarray and cmp
the comparison function. The following must be true for all x
, y
, z
in a
:
cmp x y
> 0 if and only if cmp y x
< 0cmp x y
>= 0 and cmp y z
>= 0 then cmp x z
>= 0When sort
returns, a
contains the same elements as before, reordered in such a way that for all i and j valid indices of a
:
cmp a.(i) a.(j)
>= 0 if and only if i >= jval stable_sort : (float -> float -> int) -> t -> unit
Same as sort
, but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space.
The current implementation uses Merge Sort. It uses a temporary floatarray of length n/2
, where n
is the length of the floatarray. It is usually faster than the current implementation of sort
.
val fast_sort : (float -> float -> int) -> t -> unit
Same as sort
or stable_sort
, whichever is faster on typical input.
val to_seq : t -> float Stdlib.Seq.t
Iterate on the floatarray, in increasing order. Modifications of the floatarray during iteration will be reflected in the sequence.
val to_seqi : t -> (int * float) Stdlib.Seq.t
Iterate on the floatarray, in increasing order, yielding indices along elements. Modifications of the floatarray during iteration will be reflected in the sequence.
val of_seq : float Stdlib.Seq.t -> t
Create an array from the generator.
val map_to_array : (float -> 'a) -> t -> 'a array
map_to_array f a
applies function f
to all the elements of a
, and builds an array with the results returned by f
: [| f a.(0); f a.(1); ...; f a.(length a - 1) |]
.
val map_from_array : ('a -> float) -> 'a array -> t
map_from_array f a
applies function f
to all the elements of a
, and builds a floatarray with the results returned by f
.
Care must be taken when concurrently accessing float arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results.
Every float array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays.
For example, consider the following program:
let size = 100_000_000
+let a = Float.Array.make size 1.
+let update a f () =
+ Float.Array.iteri (fun i x -> Float.Array.set a i (f x)) a
+let d1 = Domain.spawn (update a (fun x -> x +. 1.))
+let d2 = Domain.spawn (update a (fun x -> 2. *. x +. 1.))
+let () = Domain.join d1; Domain.join d2
After executing this code, each field of the float array a
is either 2.
, 3.
, 4.
or 5.
. If atomicity is required, then the user must implement their own synchronization (for example, using Mutex.t
).
If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains.
A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains.
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements.
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location with a few exceptions.
Float arrays have two supplementary caveats in the presence of data races.
First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution.
For instance, at the end of
let zeros = Float.Array.make size 0.
+let max_floats = Float.Array.make size Float.max_float
+let res = Float.Array.copy zeros
+let d1 = Domain.spawn (fun () -> Float.Array.blit zeros 0 res 0 size)
+let d2 = Domain.spawn (fun () -> Float.Array.blit max_floats 0 res 0 size)
+let () = Domain.join d1; Domain.join d2
the res
float array might contain values that are neither 0.
nor max_float
.
Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation.
Float.ArrayLabels
Float arrays with packed representation (labeled functions).
val length : t -> int
Return the length (number of elements) of the given floatarray.
val get : t -> int -> float
get a n
returns the element number n
of floatarray a
.
val set : t -> int -> float -> unit
set a n x
modifies floatarray a
in place, replacing element number n
with x
.
val make : int -> float -> t
make n x
returns a fresh floatarray of length n
, initialized with x
.
val create : int -> t
create n
returns a fresh floatarray of length n
, with uninitialized data.
val init : int -> f:(int -> float) -> t
init n ~f
returns a fresh floatarray of length n
, with element number i
initialized to the result of f i
. In other terms, init n ~f
tabulates the results of f
applied to the integers 0
to n-1
.
append v1 v2
returns a fresh floatarray containing the concatenation of the floatarrays v1
and v2
.
sub a ~pos ~len
returns a fresh floatarray of length len
, containing the elements number pos
to pos + len - 1
of floatarray a
.
copy a
returns a copy of a
, that is, a fresh floatarray containing the same elements as a
.
val fill : t -> pos:int -> len:int -> float -> unit
fill a ~pos ~len x
modifies the floatarray a
in place, storing x
in elements number pos
to pos + len - 1
.
blit ~src ~src_pos ~dst ~dst_pos ~len
copies len
elements from floatarray src
, starting at element number src_pos
, to floatarray dst
, starting at element number dst_pos
. It works correctly even if src
and dst
are the same floatarray, and the source and destination chunks overlap.
val to_list : t -> float list
to_list a
returns the list of all the elements of a
.
val of_list : float list -> t
of_list l
returns a fresh floatarray containing the elements of l
.
val iter : f:(float -> unit) -> t -> unit
iter ~f a
applies function f
in turn to all the elements of a
. It is equivalent to f a.(0); f a.(1); ...; f a.(length a - 1); ()
.
val iteri : f:(int -> float -> unit) -> t -> unit
Same as iter
, but the function is applied with the index of the element as first argument, and the element itself as second argument.
map ~f a
applies function f
to all the elements of a
, and builds a floatarray with the results returned by f
.
val map_inplace : f:(float -> float) -> t -> unit
map_inplace f a
applies function f
to all elements of a
, and updates their values in place.
Same as map
, but the function is applied to the index of the element as first argument, and the element itself as second argument.
val mapi_inplace : f:(int -> float -> float) -> t -> unit
Same as map_inplace
, but the function is applied to the index of the element as first argument, and the element itself as second argument.
val fold_left : f:('acc -> float -> 'acc) -> init:'acc -> t -> 'acc
fold_left ~f x ~init
computes f (... (f (f x init.(0)) init.(1)) ...) init.(n-1)
, where n
is the length of the floatarray init
.
val fold_right : f:(float -> 'acc -> 'acc) -> t -> init:'acc -> 'acc
fold_right f a init
computes f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))
, where n
is the length of the floatarray a
.
Array.iter2 ~f a b
applies function f
to all the elements of a
and b
.
map2 ~f a b
applies function f
to all the elements of a
and b
, and builds a floatarray with the results returned by f
: [| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]
.
val for_all : f:(float -> bool) -> t -> bool
for_all ~f [|a1; ...; an|]
checks if all elements of the floatarray satisfy the predicate f
. That is, it returns (f a1) && (f a2) && ... && (f an)
.
val exists : f:(float -> bool) -> t -> bool
exists f [|a1; ...; an|]
checks if at least one element of the floatarray satisfies the predicate f
. That is, it returns (f a1) || (f a2) || ... || (f an)
.
val mem : float -> set:t -> bool
mem a ~set
is true if and only if there is an element of set
that is structurally equal to a
, i.e. there is an x
in set
such that compare a x = 0
.
val mem_ieee : float -> set:t -> bool
Same as mem
, but uses IEEE equality instead of structural equality.
val find_opt : f:(float -> bool) -> t -> float option
val find_index : f:(float -> bool) -> t -> int option
find_index ~f a
returns Some i
, where i
is the index of the first element of the array a
that satisfies f x
, if there is such an element.
It returns None
if there is no such element.
val find_map : f:(float -> 'a option) -> t -> 'a option
val find_mapi : f:(int -> float -> 'a option) -> t -> 'a option
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
val sort : cmp:(float -> float -> int) -> t -> unit
Sort a floatarray in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, Stdlib.compare
is a suitable comparison function. After calling sort
, the array is sorted in place in increasing order. sort
is guaranteed to run in constant heap space and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant stack space.
Specification of the comparison function: Let a
be the floatarray and cmp
the comparison function. The following must be true for all x
, y
, z
in a
:
cmp x y
> 0 if and only if cmp y x
< 0cmp x y
>= 0 and cmp y z
>= 0 then cmp x z
>= 0When sort
returns, a
contains the same elements as before, reordered in such a way that for all i and j valid indices of a
:
cmp a.(i) a.(j)
>= 0 if and only if i >= jval stable_sort : cmp:(float -> float -> int) -> t -> unit
Same as sort
, but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space.
The current implementation uses Merge Sort. It uses a temporary floatarray of length n/2
, where n
is the length of the floatarray. It is usually faster than the current implementation of sort
.
val fast_sort : cmp:(float -> float -> int) -> t -> unit
Same as sort
or stable_sort
, whichever is faster on typical input.
val to_seq : t -> float Stdlib.Seq.t
Iterate on the floatarray, in increasing order. Modifications of the floatarray during iteration will be reflected in the sequence.
val to_seqi : t -> (int * float) Stdlib.Seq.t
Iterate on the floatarray, in increasing order, yielding indices along elements. Modifications of the floatarray during iteration will be reflected in the sequence.
val of_seq : float Stdlib.Seq.t -> t
Create an array from the generator.
val map_to_array : f:(float -> 'a) -> t -> 'a array
map_to_array ~f a
applies function f
to all the elements of a
, and builds an array with the results returned by f
: [| f a.(0); f a.(1); ...; f a.(length a - 1) |]
.
val map_from_array : f:('a -> float) -> 'a array -> t
map_from_array ~f a
applies function f
to all the elements of a
, and builds a floatarray with the results returned by f
.
Care must be taken when concurrently accessing float arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results.
Every float array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays.
For example, consider the following program:
let size = 100_000_000
+let a = Float.ArrayLabels.make size 1.
+let update a f () =
+ Float.ArrayLabels.iteri ~f:(fun i x -> Float.Array.set a i (f x)) a
+let d1 = Domain.spawn (update a (fun x -> x +. 1.))
+let d2 = Domain.spawn (update a (fun x -> 2. *. x +. 1.))
+let () = Domain.join d1; Domain.join d2
After executing this code, each field of the float array a
is either 2.
, 3.
, 4.
or 5.
. If atomicity is required, then the user must implement their own synchronization (for example, using Mutex.t
).
If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains.
A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains.
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements.
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location with a few exceptions.
Float arrays have two supplementary caveats in the presence of data races.
First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution.
For instance, at the end of
let zeros = Float.Array.make size 0.
+let max_floats = Float.Array.make size Float.max_float
+let res = Float.Array.copy zeros
+let d1 = Domain.spawn (fun () -> Float.Array.blit zeros 0 res 0 size)
+let d2 = Domain.spawn (fun () -> Float.Array.blit max_floats 0 res 0 size)
+let () = Domain.join d1; Domain.join d2
the res
float array might contain values that are neither 0.
nor max_float
.
Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation.
Stdlib_alerting.Float
include sig ... end
fma x y z
returns x * y + z
, with a best effort for computing this expression with a single rounding, using either hardware instructions (providing full IEEE compliance) or a software emulation.
On 64-bit Cygwin, 64-bit mingw-w64 and MSVC 2017 and earlier, this function may be emulated owing to known bugs on limitations on these platforms. Note: since software emulation of the fma is costly, make sure that you are using hardware fma support if performance matters.
rem a b
returns the remainder of a
with respect to b
. The returned value is a -. n *. b
, where n
is the quotient a /. b
rounded towards zero to an integer.
succ x
returns the floating point number right after x
i.e., the smallest floating-point number greater than x
. See also next_after
.
pred x
returns the floating-point number right before x
i.e., the greatest floating-point number smaller than x
. See also next_after
.
A special floating-point value denoting the result of an undefined operation such as 0.0 /. 0.0
. Stands for 'not a number'. Any floating-point operation with nan
as argument returns nan
as result, unless otherwise specified in IEEE 754 standard. As for floating-point comparisons, =
, <
, <=
, >
and >=
return false
and <>
returns true
if one or both of their arguments is nan
.
nan
is quiet_nan
since 5.1; it was a signaling NaN before.
Signaling NaN. The corresponding signals do not raise OCaml exception, but the value can be useful for interoperability with C libraries.
The difference between 1.0
and the smallest exactly representable floating-point number greater than 1.0
.
is_finite x
is true
if and only if x
is finite i.e., not infinite and not nan
.
is_infinite x
is true
if and only if x
is infinity
or neg_infinity
.
is_nan x
is true
if and only if x
is not a number (see nan
).
Truncate the given floating-point number to an integer. The result is unspecified if the argument is nan
or falls outside the range of representable integers.
Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by 0x
or 0X
). The format of decimal floating-point numbers is [-] dd.ddd (e|E) [+|-] dd
, where d
stands for a decimal digit. The format of hexadecimal floating-point numbers is [-] 0(x|X) hh.hhh (p|P) [+|-] dd
, where h
stands for an hexadecimal digit and d
for a decimal digit. In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional. The _
(underscore) character can appear anywhere in the string and is ignored. Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon.
Return a string representation of a floating-point number.
This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see Printf
.
This function is an alias for Stdlib.string_of_float
.
The five classes of floating-point numbers, as determined by the classify_float
function.
val classify_float : float -> fpclass
Return the class of the given floating-point number: normal, subnormal, zero, infinite, or not a number.
expm1 x
computes exp x -. 1.0
, giving numerically-accurate results even if x
is close to 0.0
.
log1p x
computes log(1.0 +. x)
(natural logarithm), giving numerically-accurate results even if x
is close to 0.0
.
Arc cosine. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and is between 0.0
and pi
.
Arc sine. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and is between -pi/2
and pi/2
.
atan2 y x
returns the arc tangent of y /. x
. The signs of x
and y
are used to determine the quadrant of the result. Result is in radians and is between -pi
and pi
.
hypot x y
returns sqrt(x *. x +. y *. y)
, that is, the length of the hypotenuse of a right-angled triangle with sides of length x
and y
, or, equivalently, the distance of the point (x,y)
to origin. If one of x
or y
is infinite, returns infinity
even if the other is nan
.
Hyperbolic arc cosine. The argument must fall within the range [1.0, inf]
. Result is in radians and is between 0.0
and inf
.
Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians.
Hyperbolic arc tangent. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and ranges over the entire real line.
Error function. The argument ranges over the entire real line. The result is always within [-1.0, 1.0]
.
Complementary error function (erfc x = 1 - erf x
). The argument ranges over the entire real line. The result is always within [-1.0, 1.0]
.
trunc x
rounds x
to the nearest integer whose absolute value is less than or equal to x
.
round x
rounds x
to the nearest integer with ties (fractional values of 0.5) rounded away from zero, regardless of the current rounding direction. If x
is an integer, +0.
, -0.
, nan
, or infinite, x
itself is returned.
On 64-bit mingw-w64, this function may be emulated owing to a bug in the C runtime library (CRT) on this platform.
Round above to an integer value. ceil f
returns the least integer value greater than or equal to f
. The result is returned as a float.
Round below to an integer value. floor f
returns the greatest integer value less than or equal to f
. The result is returned as a float.
next_after x y
returns the next representable floating-point value following x
in the direction of y
. More precisely, if y
is greater (resp. less) than x
, it returns the smallest (resp. largest) representable number greater (resp. less) than x
. If x
equals y
, the function returns y
. If x
or y
is nan
, a nan
is returned. Note that next_after max_float infinity = infinity
and that next_after 0. infinity
is the smallest denormalized positive number. If x
is the smallest denormalized positive number, next_after x 0. = 0.
copy_sign x y
returns a float whose absolute value is that of x
and whose sign is that of y
. If x
is nan
, returns nan
. If y
is nan
, returns either x
or -. x
, but it is not specified which.
sign_bit x
is true
if and only if the sign bit of x
is set. For example sign_bit 1.
and signbit 0.
are false
while sign_bit (-1.)
and sign_bit (-0.)
are true
.
frexp f
returns the pair of the significant and the exponent of f
. When f
is zero, the significant x
and the exponent n
of f
are equal to zero. When f
is non-zero, they are defined by f = x *. 2 ** n
and 0.5 <= x < 1.0
.
compare x y
returns 0
if x
is equal to y
, a negative integer if x
is less than y
, and a positive integer if x
is greater than y
. compare
treats nan
as equal to itself and less than any other float value. This treatment of nan
ensures that compare
defines a total ordering relation.
min x y
returns the minimum of x
and y
. It returns nan
when x
or y
is nan
. Moreover min (-0.) (+0.) = -0.
max x y
returns the maximum of x
and y
. It returns nan
when x
or y
is nan
. Moreover max (-0.) (+0.) = +0.
min_max x y
is (min x y, max x y)
, just more efficient.
min_num x y
returns the minimum of x
and y
treating nan
as missing values. If both x
and y
are nan
, nan
is returned. Moreover min_num (-0.) (+0.) = -0.
max_num x y
returns the maximum of x
and y
treating nan
as missing values. If both x
and y
are nan
nan
is returned. Moreover max_num (-0.) (+0.) = +0.
min_max_num x y
is (min_num x y, max_num x y)
, just more efficient. Note that in particular min_max_num x nan = (x, x)
and min_max_num nan y = (y, y)
.
val seeded_hash : int -> t -> int
A seeded hash function for floats, with the same output value as Hashtbl.seeded_hash
. This function allows this module to be passed as argument to the functor Hashtbl.MakeSeeded
.
val hash : t -> int
An unseeded hash function for floats, with the same output value as Hashtbl.hash
. This function allows this module to be passed as argument to the functor Hashtbl.Make
.
module Array : sig ... end
Float arrays with packed representation.
module ArrayLabels : sig ... end
Float arrays with packed representation (labeled functions).
Make.H
val hash : t -> int
A hashing function on keys. It must be such that if two keys are equal according to equal
, then they have identical hash values as computed by hash
. Examples: suitable (equal
, hash
) pairs for arbitrary key types include
Hashtbl.Make
Functor building an implementation of the hashtable structure. The functor Hashtbl.Make
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. Since the hash function is not seeded, the create
operation of the result structure always returns non-randomized hash tables.
module H : HashedType
type key = H.t
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
MakeSeeded.H
val seeded_hash : int -> t -> int
A seeded hashing function on keys. The first argument is the seed. It must be the case that if equal x y
is true, then seeded_hash seed x = seeded_hash seed y
for any value of seed
. A suitable choice for seeded_hash
is the function Hashtbl.seeded_hash
below.
Hashtbl.MakeSeeded
Functor building an implementation of the hashtable structure. The functor Hashtbl.MakeSeeded
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. The create
operation of the result structure supports the ~random
optional parameter and returns randomized hash tables if ~random:true
is passed or if randomization is globally on (see Hashtbl.randomize
).
module H : SeededHashedType
type key = H.t
val create : ?random:bool -> int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
Stdlib_alerting.Hashtbl
include sig ... end
Hashtbl.hash x
associates a nonnegative integer to any value of any type. It is guaranteed that if x = y
or Stdlib.compare x y = 0
, then hash x = hash y
. Moreover, hash
always terminates, even on cyclic structures.
A variant of hash
that is further parameterized by an integer seed.
Hashtbl.hash_param meaningful total x
computes a hash value for x
, with the same properties as for hash
. The two extra integer parameters meaningful
and total
give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure x
, stopping after meaningful
meaningful nodes were encountered, or total
nodes (meaningful or not) were encountered. If total
as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of meaningful
and total
means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters meaningful
and total
govern the tradeoff between accuracy and speed. As default choices, hash
and seeded_hash
take meaningful = 10
and total = 100
.
A variant of hash_param
that is further parameterized by an integer seed. Usage: Hashtbl.seeded_hash_param meaningful total seed x
.
val create : ?random:bool -> int -> ('a, 'b) t
Hashtbl.create n
creates a new, empty hash table, with initial size n
. For best results, n
should be on the order of the expected number of elements that will be in the table. The table grows as needed, so n
is just an initial guess.
The optional ~random
parameter (a boolean) controls whether the internal organization of the hash table is randomized at each execution of Hashtbl.create
or deterministic over all executions.
A hash table that is created with ~random
set to false
uses a fixed hash function (hash
) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down.
A hash table that is created with ~random
set to true
uses the seeded hash function seeded_hash
with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among 2^{30}
different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using fold
or iter
is no longer deterministic: elements are enumerated in different orders at different runs of the program.
If no ~random
parameter is given, hash tables are created in non-random mode by default. This default can be changed either programmatically by calling randomize
or by setting the R
flag in the OCAMLRUNPARAM
environment variable.
val clear : ('a, 'b) t -> unit
Empty a hash table. Use reset
instead of clear
to shrink the size of the bucket table to its initial size.
val reset : ('a, 'b) t -> unit
Empty a hash table and shrink the size of the bucket table to its initial size.
val add : ('a, 'b) t -> 'a -> 'b -> unit
Hashtbl.add tbl key data
adds a binding of key
to data
in table tbl
.
Warning: Previous bindings for key
are not removed, but simply hidden. That is, after performing remove
tbl key
, the previous binding for key
, if any, is restored. (Same behavior as with association lists.)
If you desire the classic behavior of replacing elements, see replace
.
val find : ('a, 'b) t -> 'a -> 'b
Hashtbl.find tbl x
returns the current binding of x
in tbl
, or raises Not_found
if no such binding exists.
val find_opt : ('a, 'b) t -> 'a -> 'b option
Hashtbl.find_opt tbl x
returns the current binding of x
in tbl
, or None
if no such binding exists.
val find_all : ('a, 'b) t -> 'a -> 'b list
Hashtbl.find_all tbl x
returns the list of all data associated with x
in tbl
. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table.
val mem : ('a, 'b) t -> 'a -> bool
Hashtbl.mem tbl x
checks if x
is bound in tbl
.
val remove : ('a, 'b) t -> 'a -> unit
Hashtbl.remove tbl x
removes the current binding of x
in tbl
, restoring the previous binding if it exists. It does nothing if x
is not bound in tbl
.
val replace : ('a, 'b) t -> 'a -> 'b -> unit
val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit
Hashtbl.iter f tbl
applies f
to all bindings in table tbl
. f
receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to f
.
The order in which the bindings are passed to f
is unspecified. However, if the table contains several bindings for the same key, they are passed to f
in reverse order of introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.
The behavior is not specified if the hash table is modified by f
during the iteration.
val filter_map_inplace : ('a -> 'b -> 'b option) -> ('a, 'b) t -> unit
Hashtbl.filter_map_inplace f tbl
applies f
to all bindings in table tbl
and update each binding depending on the result of f
. If f
returns None
, the binding is discarded. If it returns Some new_val
, the binding is update to associate the key to new_val
.
Other comments for iter
apply as well.
val fold : ('a -> 'b -> 'acc -> 'acc) -> ('a, 'b) t -> 'acc -> 'acc
Hashtbl.fold f tbl init
computes (f kN dN ... (f k1 d1 init)...)
, where k1 ... kN
are the keys of all bindings in tbl
, and d1 ... dN
are the associated values. Each binding is presented exactly once to f
.
The order in which the bindings are passed to f
is unspecified. However, if the table contains several bindings for the same key, they are passed to f
in reverse order of introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.
The behavior is not specified if the hash table is modified by f
during the iteration.
val length : ('a, 'b) t -> int
Hashtbl.length tbl
returns the number of bindings in tbl
. It takes constant time. Multiple bindings are counted once each, so Hashtbl.length
gives the number of times Hashtbl.iter
calls its first argument.
After a call to Hashtbl.randomize()
, hash tables are created in randomized mode by default: create
returns randomized hash tables, unless the ~random:false
optional parameter is given. The same effect can be achieved by setting the R
parameter in the OCAMLRUNPARAM
environment variable.
It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in create
call Hashtbl.randomize()
at initialization time before any domains are created.
Note that once Hashtbl.randomize()
was called, there is no way to revert to the non-randomized default behavior of create
. This is intentional. Non-randomized hash tables can still be created using Hashtbl.create ~random:false
.
Return true
if the tables are currently created in randomized mode by default, false
otherwise.
Return a copy of the given hashtable. Unlike copy
, rebuild
h
re-hashes all the (key, value) entries of the original table h
. The returned hash table is randomized if h
was randomized, or the optional random
parameter is true, or if the default is to create randomized hash tables; see create
for more information.
rebuild
can safely be used to import a hash table built by an old version of the Hashtbl
module, then marshaled to persistent storage. After unmarshaling, apply rebuild
to produce a hash table for the current version of the Hashtbl
module.
type statistics = {
num_bindings : int;
num_buckets : int;
Number of buckets in the table.
*)max_bucket_length : int;
Maximal number of bindings per bucket.
*)bucket_histogram : int array;
Histogram of bucket sizes. This array histo
has length max_bucket_length + 1
. The value of histo.(i)
is the number of buckets whose size is i
.
}
val stats : ('a, 'b) t -> statistics
Hashtbl.stats tbl
returns statistics about the table tbl
: number of buckets, size of the biggest bucket, distribution of buckets by size.
val to_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t
Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first.
The behavior is not specified if the hash table is modified during the iteration.
val to_seq_keys : ('a, _) t -> 'a Stdlib.Seq.t
Same as Seq.map fst (to_seq m)
val to_seq_values : (_, 'b) t -> 'b Stdlib.Seq.t
Same as Seq.map snd (to_seq m)
val add_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t -> unit
Add the given bindings to the table, using add
val replace_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t -> unit
Add the given bindings to the table, using replace
val of_seq : ('a * 'b) Stdlib.Seq.t -> ('a, 'b) t
Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using replace_seq
, which means that if two pairs have the same key, only the latest one will appear in the table.
module type HashedType = sig ... end
The input signature of the functor Make
.
Functor building an implementation of the hashtable structure. The functor Hashtbl.Make
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. Since the hash function is not seeded, the create
operation of the result structure always returns non-randomized hash tables.
module type SeededHashedType = sig ... end
The input signature of the functor MakeSeeded
.
module type SeededS = sig ... end
The output signature of the functor MakeSeeded
.
module MakeSeeded (H : SeededHashedType) : SeededS with type key = H.t
Functor building an implementation of the hashtable structure. The functor Hashtbl.MakeSeeded
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. The create
operation of the result structure supports the ~random
optional parameter and returns randomized hash tables if ~random:true
is passed or if randomization is globally on (see Hashtbl.randomize
).
Hashtbl.HashedType
The input signature of the functor Make
.
val hash : t -> int
A hashing function on keys. It must be such that if two keys are equal according to equal
, then they have identical hash values as computed by hash
. Examples: suitable (equal
, hash
) pairs for arbitrary key types include
Hashtbl.S
The output signature of the functor Make
.
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
Hashtbl.SeededHashedType
The input signature of the functor MakeSeeded
.
val seeded_hash : int -> t -> int
A seeded hashing function on keys. The first argument is the seed. It must be the case that if equal x y
is true, then seeded_hash seed x = seeded_hash seed y
for any value of seed
. A suitable choice for seeded_hash
is the function Hashtbl.seeded_hash
below.
Hashtbl.SeededS
The output signature of the functor MakeSeeded
.
val create : ?random:bool -> int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
Stdlib_alerting.LargeFile
Operations on large files. This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type int64
) instead of regular integers (type int
), these alternate functions allow operating on files whose sizes are greater than max_int
.
val seek_out : out_channel -> int64 -> unit
val pos_out : out_channel -> int64
val out_channel_length : out_channel -> int64
val seek_in : in_channel -> int64 -> unit
val pos_in : in_channel -> int64
val in_channel_length : in_channel -> int64
Stdlib_alerting.List
include sig ... end
Compare the lengths of two lists. compare_lengths l1 l2
is equivalent to compare (length l1) (length l2)
, except that the computation stops after reaching the end of the shortest list.
Compare the length of a list to an integer. compare_length_with l len
is equivalent to compare (length l) len
, except that the computation stops after at most len
iterations on the list.
is_empty l
is true if and only if l
has no elements. It is equivalent to compare_length_with l 0 = 0
.
Return the n
-th element of the given list. The first element (head of the list) is at position 0.
Return the n
-th element of the given list. The first element (head of the list) is at position 0. Return None
if the list is too short.
init len f
is [f 0; f 1; ...; f (len-1)]
, evaluated left to right.
append l0 l1
appends l1
to l0
. Same function as the infix operator @
.
rev_append l1 l2
reverses l1
and concatenates it with l2
. This is equivalent to (
rev
l1) @ l2
.
Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument + length of the longest sub-list).
Same as concat
. Not tail-recursive (length of the argument + length of the longest sub-list).
equal eq [a1; ...; an] [b1; ..; bm]
holds when the two input lists have the same length, and for each pair of elements ai
, bi
at the same position we have eq ai bi
.
Note: the eq
function may be called even if the lists have different length. If you know your equality function is costly, you may want to check compare_lengths
first.
compare cmp [a1; ...; an] [b1; ...; bm]
performs a lexicographic comparison of the two input lists, using the same 'a -> 'a -> int
interface as Stdlib.compare
:
a1 :: l1
is smaller than a2 :: l2
(negative result) if a1
is smaller than a2
, or if they are equal (0 result) and l1
is smaller than l2
[]
is strictly smaller than non-empty listsNote: the cmp
function will be called even if the lists have different lengths.
iter f [a1; ...; an]
applies function f
in turn to [a1; ...; an]
. It is equivalent to f a1; f a2; ...; f an
.
Same as iter
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
map f [a1; ...; an]
applies function f
to a1, ..., an
, and builds the list [f a1; ...; f an]
with the results returned by f
.
Same as map
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
filter_map f l
applies f
to every element of l
, filters out the None
elements and returns the list of the arguments of the Some
elements.
fold_left_map
is a combination of fold_left
and map
that threads an accumulator through calls to f
.
fold_left f init [b1; ...; bn]
is f (... (f (f init b1) b2) ...) bn
.
fold_right f [a1; ...; an] init
is f a1 (f a2 (... (f an init) ...))
. Not tail-recursive.
iter2 f [a1; ...; an] [b1; ...; bn]
calls in turn f a1 b1; ...; f an bn
.
map2 f [a1; ...; an] [b1; ...; bn]
is [f a1 b1; ...; f an bn]
.
fold_left2 f init [a1; ...; an] [b1; ...; bn]
is f (... (f (f init a1 b1) a2 b2) ...) an bn
.
fold_right2 f [a1; ...; an] [b1; ...; bn] init
is f a1 b1 (f a2 b2 (... (f an bn init) ...))
.
for_all f [a1; ...; an]
checks if all elements of the list satisfy the predicate f
. That is, it returns (f a1) && (f a2) && ... && (f an)
for a non-empty list and true
if the list is empty.
exists f [a1; ...; an]
checks if at least one element of the list satisfies the predicate f
. That is, it returns (f a1) || (f a2) || ... || (f an)
for a non-empty list and false
if the list is empty.
Same as for_all
, but for a two-argument predicate.
Same as exists
, but for a two-argument predicate.
find f l
returns the first element of the list l
that satisfies the predicate f
.
find f l
returns the first element of the list l
that satisfies the predicate f
. Returns None
if there is no value that satisfies f
in the list l
.
find_index f xs
returns Some i
, where i
is the index of the first element of the list xs
that satisfies f x
, if there is such an element.
It returns None
if there is no such element.
find_map f l
applies f
to the elements of l
in order, and returns the first result of the form Some v
, or None
if none exist.
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
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 is preserved.
find_all
is another name for filter
.
Same as filter
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
partition f l
returns a pair of lists (l1, l2)
, where l1
is the list of all the elements of l
that satisfy the predicate f
, and l2
is the list of all the elements of l
that do not satisfy f
. The order of the elements in the input list is preserved.
partition_map f l
returns a pair of lists (l1, l2)
such that, for each element x
of the input list l
:
f x
is Left y1
, then y1
is in l1
, andf x
is Right y2
, then y2
is in l2
.The output elements are included in l1
and l2
in the same relative order as the corresponding input elements in l
.
In particular, partition_map (fun x -> if f x then Left x else Right x) l
is equivalent to partition f l
.
assoc a l
returns the value associated with key a
in the list of pairs l
. That is, assoc a [ ...; (a,b); ...] = b
if (a,b)
is the leftmost binding of a
in list l
.
assoc_opt a l
returns the value associated with key a
in the list of pairs l
. That is, assoc_opt a [ ...; (a,b); ...] = Some b
if (a,b)
is the leftmost binding of a
in list l
. Returns None
if there is no value associated with a
in the list l
.
Same as assoc
, but simply return true
if a binding exists, and false
if no bindings exist for the given key.
remove_assoc a l
returns the list of pairs l
without the first pair with key a
, if any. Not tail-recursive.
Transform a list of pairs into a pair of lists: split [(a1,b1); ...; (an,bn)]
is ([a1; ...; an], [b1; ...; bn])
. Not tail-recursive.
Transform a pair of lists into a list of pairs: combine [a1; ...; an] [b1; ...; bn]
is [(a1,b1); ...; (an,bn)]
.
Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, Stdlib.compare
is a suitable comparison function. The resulting list is sorted in increasing order. sort
is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space.
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
, but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order).
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
or stable_sort
, whichever is faster on typical input.
Same as sort
, but also remove duplicates.
Merge two lists: Assuming that l1
and l2
are sorted according to the comparison function cmp
, merge cmp l1 l2
will return a sorted list containing all the elements of l1
and l2
. If several elements compare equal, the elements of l1
will be before the elements of l2
. Not tail-recursive (sum of the lengths of the arguments).
Same as mem
, but uses physical equality instead of structural equality to compare list elements.
Same as assoc
, but uses physical equality instead of structural equality to compare keys.
Same as assoc_opt
, but uses physical equality instead of structural equality to compare keys.
Same as mem_assoc
, but uses physical equality instead of structural equality to compare keys.
Same as remove_assoc
, but uses physical equality instead of structural equality to compare keys. Not tail-recursive.
Stdlib_alerting.ListLabels
include sig ... end
Compare the lengths of two lists. compare_lengths l1 l2
is equivalent to compare (length l1) (length l2)
, except that the computation stops after reaching the end of the shortest list.
Compare the length of a list to an integer. compare_length_with l len
is equivalent to compare (length l) len
, except that the computation stops after at most len
iterations on the list.
is_empty l
is true if and only if l
has no elements. It is equivalent to compare_length_with l 0 = 0
.
Return the n
-th element of the given list. The first element (head of the list) is at position 0.
Return the n
-th element of the given list. The first element (head of the list) is at position 0. Return None
if the list is too short.
init ~len ~f
is [f 0; f 1; ...; f (len-1)]
, evaluated left to right.
append l0 l1
appends l1
to l0
. Same function as the infix operator @
.
rev_append l1 l2
reverses l1
and concatenates it with l2
. This is equivalent to (
rev
l1) @ l2
.
Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument + length of the longest sub-list).
Same as concat
. Not tail-recursive (length of the argument + length of the longest sub-list).
equal eq [a1; ...; an] [b1; ..; bm]
holds when the two input lists have the same length, and for each pair of elements ai
, bi
at the same position we have eq ai bi
.
Note: the eq
function may be called even if the lists have different length. If you know your equality function is costly, you may want to check compare_lengths
first.
compare cmp [a1; ...; an] [b1; ...; bm]
performs a lexicographic comparison of the two input lists, using the same 'a -> 'a -> int
interface as Stdlib.compare
:
a1 :: l1
is smaller than a2 :: l2
(negative result) if a1
is smaller than a2
, or if they are equal (0 result) and l1
is smaller than l2
[]
is strictly smaller than non-empty listsNote: the cmp
function will be called even if the lists have different lengths.
iter ~f [a1; ...; an]
applies function f
in turn to [a1; ...; an]
. It is equivalent to f a1; f a2; ...; f an
.
Same as iter
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
map ~f [a1; ...; an]
applies function f
to a1, ..., an
, and builds the list [f a1; ...; f an]
with the results returned by f
.
Same as map
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
filter_map ~f l
applies f
to every element of l
, filters out the None
elements and returns the list of the arguments of the Some
elements.
fold_left_map
is a combination of fold_left
and map
that threads an accumulator through calls to f
.
fold_left ~f ~init [b1; ...; bn]
is f (... (f (f init b1) b2) ...) bn
.
fold_right ~f [a1; ...; an] ~init
is f a1 (f a2 (... (f an init) ...))
. Not tail-recursive.
iter2 ~f [a1; ...; an] [b1; ...; bn]
calls in turn f a1 b1; ...; f an bn
.
map2 ~f [a1; ...; an] [b1; ...; bn]
is [f a1 b1; ...; f an bn]
.
fold_left2 ~f ~init [a1; ...; an] [b1; ...; bn]
is f (... (f (f init a1 b1) a2 b2) ...) an bn
.
fold_right2 ~f [a1; ...; an] [b1; ...; bn] ~init
is f a1 b1 (f a2 b2 (... (f an bn init) ...))
.
for_all ~f [a1; ...; an]
checks if all elements of the list satisfy the predicate f
. That is, it returns (f a1) && (f a2) && ... && (f an)
for a non-empty list and true
if the list is empty.
exists ~f [a1; ...; an]
checks if at least one element of the list satisfies the predicate f
. That is, it returns (f a1) || (f a2) || ... || (f an)
for a non-empty list and false
if the list is empty.
Same as for_all
, but for a two-argument predicate.
Same as exists
, but for a two-argument predicate.
mem a ~set
is true if and only if a
is equal to an element of set
.
find ~f l
returns the first element of the list l
that satisfies the predicate f
.
find ~f l
returns the first element of the list l
that satisfies the predicate f
. Returns None
if there is no value that satisfies f
in the list l
.
find_index ~f xs
returns Some i
, where i
is the index of the first element of the list xs
that satisfies f x
, if there is such an element.
It returns None
if there is no such element.
find_map ~f l
applies f
to the elements of l
in order, and returns the first result of the form Some v
, or None
if none exist.
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
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 is preserved.
find_all
is another name for filter
.
Same as filter
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
partition ~f l
returns a pair of lists (l1, l2)
, where l1
is the list of all the elements of l
that satisfy the predicate f
, and l2
is the list of all the elements of l
that do not satisfy f
. The order of the elements in the input list is preserved.
partition_map f l
returns a pair of lists (l1, l2)
such that, for each element x
of the input list l
:
f x
is Left y1
, then y1
is in l1
, andf x
is Right y2
, then y2
is in l2
.The output elements are included in l1
and l2
in the same relative order as the corresponding input elements in l
.
In particular, partition_map (fun x -> if f x then Left x else Right x) l
is equivalent to partition f l
.
assoc a l
returns the value associated with key a
in the list of pairs l
. That is, assoc a [ ...; (a,b); ...] = b
if (a,b)
is the leftmost binding of a
in list l
.
assoc_opt a l
returns the value associated with key a
in the list of pairs l
. That is, assoc_opt a [ ...; (a,b); ...] = Some b
if (a,b)
is the leftmost binding of a
in list l
. Returns None
if there is no value associated with a
in the list l
.
Same as assoc
, but simply return true
if a binding exists, and false
if no bindings exist for the given key.
remove_assoc a l
returns the list of pairs l
without the first pair with key a
, if any. Not tail-recursive.
Transform a list of pairs into a pair of lists: split [(a1,b1); ...; (an,bn)]
is ([a1; ...; an], [b1; ...; bn])
. Not tail-recursive.
Transform a pair of lists into a list of pairs: combine [a1; ...; an] [b1; ...; bn]
is [(a1,b1); ...; (an,bn)]
.
Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, Stdlib.compare
is a suitable comparison function. The resulting list is sorted in increasing order. sort
is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space.
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
, but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order).
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
or stable_sort
, whichever is faster on typical input.
Same as sort
, but also remove duplicates.
Merge two lists: Assuming that l1
and l2
are sorted according to the comparison function cmp
, merge ~cmp l1 l2
will return a sorted list containing all the elements of l1
and l2
. If several elements compare equal, the elements of l1
will be before the elements of l2
. Not tail-recursive (sum of the lengths of the arguments).
Same as mem
, but uses physical equality instead of structural equality to compare list elements.
Same as assoc
, but uses physical equality instead of structural equality to compare keys.
Same as assoc_opt
, but uses physical equality instead of structural equality to compare keys.
Same as mem_assoc
, but uses physical equality instead of structural equality to compare keys.
Same as remove_assoc
, but uses physical equality instead of structural equality to compare keys. Not tail-recursive.
Make.H
val hash : t -> int
A hashing function on keys. It must be such that if two keys are equal according to equal
, then they have identical hash values as computed by hash
. Examples: suitable (equal
, hash
) pairs for arbitrary key types include
Hashtbl.Make
Functor building an implementation of the hashtable structure. The functor Hashtbl.Make
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. Since the hash function is not seeded, the create
operation of the result structure always returns non-randomized hash tables.
module H : HashedType
type key = H.t
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
MakeSeeded.H
val seeded_hash : int -> t -> int
A seeded hashing function on keys. The first argument is the seed. It must be the case that if equal x y
is true, then seeded_hash seed x = seeded_hash seed y
for any value of seed
. A suitable choice for seeded_hash
is the function Hashtbl.seeded_hash
below.
Hashtbl.MakeSeeded
Functor building an implementation of the hashtable structure. The functor Hashtbl.MakeSeeded
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. The create
operation of the result structure supports the ~random
optional parameter and returns randomized hash tables if ~random:true
is passed or if randomization is globally on (see Hashtbl.randomize
).
module H : SeededHashedType
type key = H.t
val create : ?random:bool -> int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
MoreLabels.Hashtbl
Hash tables and hash functions.
Hash tables are hashed association tables, with in-place modification. Because most operations on a hash table modify their input, they're more commonly used in imperative code. The lookup of the value associated with a key (see find
, find_opt
) is normally very fast, often faster than the equivalent lookup in Map
.
The functors Make
and MakeSeeded
can be used when performance or flexibility are key. The user provides custom equality and hash functions for the key type, and obtains a custom hash table type for this particular type of key.
Warning a hash table is only as good as the hash function. A bad hash function will turn the table into a degenerate association list, with linear time lookup instead of constant time lookup.
The polymorphic t
hash table is useful in simpler cases or in interactive environments. It uses the polymorphic hash
function defined in the OCaml runtime (at the time of writing, it's SipHash), as well as the polymorphic equality (=)
.
See the examples section.
Unsynchronized accesses
Unsynchronized accesses to a hash table may lead to an invalid hash table state. Thus, concurrent accesses to a hash tables must be synchronized (for instance with a Mutex.t
).
val create : ?random:bool -> int -> ('a, 'b) t
Hashtbl.create n
creates a new, empty hash table, with initial size n
. For best results, n
should be on the order of the expected number of elements that will be in the table. The table grows as needed, so n
is just an initial guess.
The optional ~random
parameter (a boolean) controls whether the internal organization of the hash table is randomized at each execution of Hashtbl.create
or deterministic over all executions.
A hash table that is created with ~random
set to false
uses a fixed hash function (hash
) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down.
A hash table that is created with ~random
set to true
uses the seeded hash function seeded_hash
with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among 2^{30}
different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using fold
or iter
is no longer deterministic: elements are enumerated in different orders at different runs of the program.
If no ~random
parameter is given, hash tables are created in non-random mode by default. This default can be changed either programmatically by calling randomize
or by setting the R
flag in the OCAMLRUNPARAM
environment variable.
val clear : ('a, 'b) t -> unit
Empty a hash table. Use reset
instead of clear
to shrink the size of the bucket table to its initial size.
val reset : ('a, 'b) t -> unit
Empty a hash table and shrink the size of the bucket table to its initial size.
val add : ('a, 'b) t -> key:'a -> data:'b -> unit
Hashtbl.add tbl ~key ~data
adds a binding of key
to data
in table tbl
.
Warning: Previous bindings for key
are not removed, but simply hidden. That is, after performing remove
tbl key
, the previous binding for key
, if any, is restored. (Same behavior as with association lists.)
If you desire the classic behavior of replacing elements, see replace
.
val find : ('a, 'b) t -> 'a -> 'b
Hashtbl.find tbl x
returns the current binding of x
in tbl
, or raises Not_found
if no such binding exists.
val find_opt : ('a, 'b) t -> 'a -> 'b option
Hashtbl.find_opt tbl x
returns the current binding of x
in tbl
, or None
if no such binding exists.
val find_all : ('a, 'b) t -> 'a -> 'b list
Hashtbl.find_all tbl x
returns the list of all data associated with x
in tbl
. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table.
val mem : ('a, 'b) t -> 'a -> bool
Hashtbl.mem tbl x
checks if x
is bound in tbl
.
val remove : ('a, 'b) t -> 'a -> unit
Hashtbl.remove tbl x
removes the current binding of x
in tbl
, restoring the previous binding if it exists. It does nothing if x
is not bound in tbl
.
val replace : ('a, 'b) t -> key:'a -> data:'b -> unit
val iter : f:(key:'a -> data:'b -> unit) -> ('a, 'b) t -> unit
Hashtbl.iter ~f tbl
applies f
to all bindings in table tbl
. f
receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to f
.
The order in which the bindings are passed to f
is unspecified. However, if the table contains several bindings for the same key, they are passed to f
in reverse order of introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.
The behavior is not specified if the hash table is modified by f
during the iteration.
val filter_map_inplace :
+ f:(key:'a -> data:'b -> 'b option) ->
+ ('a, 'b) t ->
+ unit
Hashtbl.filter_map_inplace ~f tbl
applies f
to all bindings in table tbl
and update each binding depending on the result of f
. If f
returns None
, the binding is discarded. If it returns Some new_val
, the binding is update to associate the key to new_val
.
Other comments for iter
apply as well.
val fold :
+ f:(key:'a -> data:'b -> 'acc -> 'acc) ->
+ ('a, 'b) t ->
+ init:'acc ->
+ 'acc
Hashtbl.fold ~f tbl ~init
computes (f kN dN ... (f k1 d1 init)...)
, where k1 ... kN
are the keys of all bindings in tbl
, and d1 ... dN
are the associated values. Each binding is presented exactly once to f
.
The order in which the bindings are passed to f
is unspecified. However, if the table contains several bindings for the same key, they are passed to f
in reverse order of introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.
The behavior is not specified if the hash table is modified by f
during the iteration.
val length : ('a, 'b) t -> int
Hashtbl.length tbl
returns the number of bindings in tbl
. It takes constant time. Multiple bindings are counted once each, so Hashtbl.length
gives the number of times Hashtbl.iter
calls its first argument.
After a call to Hashtbl.randomize()
, hash tables are created in randomized mode by default: create
returns randomized hash tables, unless the ~random:false
optional parameter is given. The same effect can be achieved by setting the R
parameter in the OCAMLRUNPARAM
environment variable.
It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in create
call Hashtbl.randomize()
at initialization time before any domains are created.
Note that once Hashtbl.randomize()
was called, there is no way to revert to the non-randomized default behavior of create
. This is intentional. Non-randomized hash tables can still be created using Hashtbl.create ~random:false
.
Return true
if the tables are currently created in randomized mode by default, false
otherwise.
Return a copy of the given hashtable. Unlike copy
, rebuild
h
re-hashes all the (key, value) entries of the original table h
. The returned hash table is randomized if h
was randomized, or the optional random
parameter is true, or if the default is to create randomized hash tables; see create
for more information.
rebuild
can safely be used to import a hash table built by an old version of the Hashtbl
module, then marshaled to persistent storage. After unmarshaling, apply rebuild
to produce a hash table for the current version of the Hashtbl
module.
type statistics = Stdlib.Hashtbl.statistics = {
num_bindings : int;
num_buckets : int;
Number of buckets in the table.
*)max_bucket_length : int;
Maximal number of bindings per bucket.
*)bucket_histogram : int array;
Histogram of bucket sizes. This array histo
has length max_bucket_length + 1
. The value of histo.(i)
is the number of buckets whose size is i
.
}
val stats : ('a, 'b) t -> statistics
Hashtbl.stats tbl
returns statistics about the table tbl
: number of buckets, size of the biggest bucket, distribution of buckets by size.
val to_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t
Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first.
The behavior is not specified if the hash table is modified during the iteration.
val to_seq_keys : ('a, _) t -> 'a Stdlib.Seq.t
Same as Seq.map fst (to_seq m)
val to_seq_values : (_, 'b) t -> 'b Stdlib.Seq.t
Same as Seq.map snd (to_seq m)
val add_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t -> unit
Add the given bindings to the table, using add
val replace_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t -> unit
Add the given bindings to the table, using replace
val of_seq : ('a * 'b) Stdlib.Seq.t -> ('a, 'b) t
Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using replace_seq
, which means that if two pairs have the same key, only the latest one will appear in the table.
The functorial interface allows the use of specific comparison and hash functions, either for performance/security concerns, or because keys are not hashable/comparable with the polymorphic builtins.
For instance, one might want to specialize a table for integer keys:
module IntHash =
+ struct
+ type t = int
+ let equal i j = i=j
+ let hash i = i land max_int
+ end
+
+module IntHashtbl = Hashtbl.Make(IntHash)
+
+let h = IntHashtbl.create 17 in
+IntHashtbl.add h 12 "hello"
This creates a new module IntHashtbl
, with a new type 'a
+ IntHashtbl.t
of tables from int
to 'a
. In this example, h
contains string
values so its type is string IntHashtbl.t
.
Note that the new type 'a IntHashtbl.t
is not compatible with the type ('a,'b) Hashtbl.t
of the generic interface. For example, Hashtbl.length h
would not type-check, you must use IntHashtbl.length
.
module type HashedType = sig ... end
The input signature of the functor Make
.
module Make
+ (H : HashedType) :
+ S with type key = H.t and type 'a t = 'a Stdlib.Hashtbl.Make(H).t
Functor building an implementation of the hashtable structure. The functor Hashtbl.Make
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. Since the hash function is not seeded, the create
operation of the result structure always returns non-randomized hash tables.
module type SeededHashedType = sig ... end
The input signature of the functor MakeSeeded
.
module type SeededS = sig ... end
The output signature of the functor MakeSeeded
.
module MakeSeeded
+ (H : SeededHashedType) :
+ SeededS with type key = H.t and type 'a t = 'a Stdlib.Hashtbl.MakeSeeded(H).t
Functor building an implementation of the hashtable structure. The functor Hashtbl.MakeSeeded
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. The create
operation of the result structure supports the ~random
optional parameter and returns randomized hash tables if ~random:true
is passed or if randomization is globally on (see Hashtbl.randomize
).
Hashtbl.hash x
associates a nonnegative integer to any value of any type. It is guaranteed that if x = y
or Stdlib.compare x y = 0
, then hash x = hash y
. Moreover, hash
always terminates, even on cyclic structures.
A variant of hash
that is further parameterized by an integer seed.
Hashtbl.hash_param meaningful total x
computes a hash value for x
, with the same properties as for hash
. The two extra integer parameters meaningful
and total
give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure x
, stopping after meaningful
meaningful nodes were encountered, or total
nodes (meaningful or not) were encountered. If total
as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of meaningful
and total
means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters meaningful
and total
govern the tradeoff between accuracy and speed. As default choices, hash
and seeded_hash
take meaningful = 10
and total = 100
.
A variant of hash_param
that is further parameterized by an integer seed. Usage: Hashtbl.seeded_hash_param meaningful total seed x
.
(* 0...99 *)
+let seq = Seq.ints 0 |> Seq.take 100
+
+(* build from Seq.t *)
+# let tbl =
+ seq
+ |> Seq.map (fun x -> x, string_of_int x)
+ |> Hashtbl.of_seq
+val tbl : (int, string) Hashtbl.t = <abstr>
+
+# Hashtbl.length tbl
+- : int = 100
+
+# Hashtbl.find_opt tbl 32
+- : string option = Some "32"
+
+# Hashtbl.find_opt tbl 166
+- : string option = None
+
+# Hashtbl.replace tbl 166 "one six six"
+- : unit = ()
+
+# Hashtbl.find_opt tbl 166
+- : string option = Some "one six six"
+
+# Hashtbl.length tbl
+- : int = 101
Given a sequence of elements (here, a Seq.t
), we want to count how many times each distinct element occurs in the sequence. A simple way to do this, assuming the elements are comparable and hashable, is to use a hash table that maps elements to their number of occurrences.
Here we illustrate that principle using a sequence of (ascii) characters (type char
). We use a custom Char_tbl
specialized for char
.
# module Char_tbl = Hashtbl.Make(struct
+ type t = char
+ let equal = Char.equal
+ let hash = Hashtbl.hash
+ end)
+
+(* count distinct occurrences of chars in [seq] *)
+# let count_chars (seq : char Seq.t) : _ list =
+ let counts = Char_tbl.create 16 in
+ Seq.iter
+ (fun c ->
+ let count_c =
+ Char_tbl.find_opt counts c
+ |> Option.value ~default:0
+ in
+ Char_tbl.replace counts c (count_c + 1))
+ seq;
+ (* turn into a list *)
+ Char_tbl.fold (fun c n l -> (c,n) :: l) counts []
+ |> List.sort (fun (c1,_)(c2,_) -> Char.compare c1 c2)
+val count_chars : Char_tbl.key Seq.t -> (Char.t * int) list = <fun>
+
+(* basic seq from a string *)
+# let seq = String.to_seq "hello world, and all the camels in it!"
+val seq : char Seq.t = <fun>
+
+# count_chars seq
+- : (Char.t * int) list =
+[(' ', 7); ('!', 1); (',', 1); ('a', 3); ('c', 1); ('d', 2); ('e', 3);
+ ('h', 2); ('i', 2); ('l', 6); ('m', 1); ('n', 2); ('o', 2); ('r', 1);
+ ('s', 1); ('t', 2); ('w', 1)]
+
+(* "abcabcabc..." *)
+# let seq2 =
+ Seq.cycle (String.to_seq "abc") |> Seq.take 31
+val seq2 : char Seq.t = <fun>
+
+# String.of_seq seq2
+- : String.t = "abcabcabcabcabcabcabcabcabcabca"
+
+# count_chars seq2
+- : (Char.t * int) list = [('a', 11); ('b', 10); ('c', 10)]
Hashtbl.HashedType
The input signature of the functor Make
.
val hash : t -> int
A hashing function on keys. It must be such that if two keys are equal according to equal
, then they have identical hash values as computed by hash
. Examples: suitable (equal
, hash
) pairs for arbitrary key types include
Hashtbl.S
The output signature of the functor Make
.
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
Hashtbl.SeededHashedType
The input signature of the functor MakeSeeded
.
val seeded_hash : int -> t -> int
A seeded hashing function on keys. The first argument is the seed. It must be the case that if equal x y
is true, then seeded_hash seed x = seeded_hash seed y
for any value of seed
. A suitable choice for seeded_hash
is the function Hashtbl.seeded_hash
below.
Hashtbl.SeededS
The output signature of the functor MakeSeeded
.
val create : ?random:bool -> int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
Make.Ord
A total ordering function over the keys. This is a two-argument function f
such that f e1 e2
is zero if the keys e1
and e2
are equal, f e1 e2
is strictly negative if e1
is smaller than e2
, and f e1 e2
is strictly positive if e1
is greater than e2
. Example: a suitable ordering function is the generic structural comparison function Stdlib.compare
.
Map.Make
Functor building an implementation of the map structure given a totally ordered type.
module Ord : OrderedType
type key = Ord.t
The type of the map keys.
val empty : 'a t
The empty map.
add ~key ~data m
returns a map containing the same bindings as m
, plus a binding of key
to data
. If key
was already bound in m
to a value that is physically equal to data
, m
is returned unchanged (the result of the function is then physically equal to m
). Otherwise, the previous binding of key
in m
disappears.
add_to_list ~key ~data m
is m
with key
mapped to l
such that l
is data :: Map.find key m
if key
was bound in m
and [v]
otherwise.
update ~key ~f m
returns a map containing the same bindings as m
, except for the binding of key
. Depending on the value of y
where y
is f (find_opt key m)
, the binding of key
is added, removed or updated. If y
is None
, the binding is removed if it exists; otherwise, if y
is Some z
then key
is associated to z
in the resulting map. If key
was already bound in m
to a value that is physically equal to z
, m
is returned unchanged (the result of the function is then physically equal to m
).
singleton x y
returns the one-element map that contains a binding y
for x
.
remove x m
returns a map containing the same bindings as m
, except for x
which is unbound in the returned map. If x
was not in m
, m
is returned unchanged (the result of the function is then physically equal to m
).
merge ~f m1 m2
computes a map whose keys are a subset of the keys of m1
and of m2
. The presence of each such binding, and the corresponding value, is determined with the function f
. In terms of the find_opt
operation, we have find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)
for any key x
, provided that f x None None = None
.
union ~f m1 m2
computes a map whose keys are a subset of the keys of m1
and of m2
. When the same binding is defined in both arguments, the function f
is used to combine them. This is a special case of merge
: union f m1 m2
is equivalent to merge f' m1 m2
, where
f' _key None None = None
f' _key (Some v) None = Some v
f' _key None (Some v) = Some v
f' key (Some v1) (Some v2) = f key v1 v2
val cardinal : 'a t -> int
Return the number of bindings of a map.
Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering Ord.compare
, where Ord
is the argument given to Map.Make
.
Return the binding with the smallest key in a given map (with respect to the Ord.compare
ordering), or raise Not_found
if the map is empty.
Return the binding with the smallest key in the given map (with respect to the Ord.compare
ordering), or None
if the map is empty.
Same as min_binding
, but returns the binding with the largest key in the given map.
Same as min_binding_opt
, but returns the binding with the largest key in the given map.
Return one binding of the given map, or raise Not_found
if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
Return one binding of the given map, or None
if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
find x m
returns the current value of x
in m
, or raises Not_found
if no binding for x
exists.
find_opt x m
returns Some v
if the current value of x
in m
is v
, or None
if no binding for x
exists.
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.
For example, find_first (fun k -> Ord.compare k x >= 0) m
will return the first binding k, v
of m
where Ord.compare k x >= 0
(intuitively: k >= x
), or raise Not_found
if x
is greater than any element of m
.
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.
find_last ~f m
, where f
is a monotonically decreasing function, returns the binding of m
with the highest key k
such that f k
, or raises Not_found
if no such key exists.
find_last_opt ~f m
, where f
is a monotonically decreasing function, returns an option containing the binding of m
with the highest key k
such that f k
, or None
if no such key exists.
iter ~f m
applies f
to all bindings in map m
. f
receives the key as first argument, and the associated value as second argument. The bindings are passed to f
in increasing order with respect to the ordering over the type of the keys.
fold ~f m ~init
computes (f kN dN ... (f k1 d1 init)...)
, where k1 ... kN
are the keys of all bindings in m
(in increasing order), and d1 ... dN
are the associated data.
map ~f m
returns a map with same domain as m
, where the associated value a
of all bindings of m
has been replaced by the result of the application of f
to a
. The bindings are passed to f
in increasing order with respect to the ordering over the type of the keys.
Same as map
, but the function receives as arguments both the key and the associated value for each binding of the map.
filter ~f m
returns the map with all the bindings in m
that satisfy predicate p
. If every binding in m
satisfies f
, m
is returned unchanged (the result of the function is then physically equal to m
)
filter_map ~f m
applies the function f
to every binding of m
, and builds a map from the results. For each binding (k, v)
in the input map:
f k v
is None
then k
is not in the result,f k v
is Some v'
then the binding (k, v')
is in the output map.For example, the following function on maps whose values are lists
filter_map
+ (fun _k li -> match li with [] -> None | _::tl -> Some tl)
+ m
drops all bindings of m
whose value is an empty list, and pops the first element of each value that is non-empty.
partition ~f m
returns a pair of maps (m1, m2)
, where m1
contains all the bindings of m
that satisfy the predicate f
, and m2
is the map with all the bindings of m
that do not satisfy f
.
split x m
returns a triple (l, data, r)
, where l
is the map with all the bindings of m
whose key is strictly less than x
; r
is the map with all the bindings of m
whose key is strictly greater than x
; data
is None
if m
contains no binding for x
, or Some v
if m
binds v
to x
.
val is_empty : 'a t -> bool
Test whether a map is empty or not.
mem x m
returns true
if m
contains a binding for x
, and false
otherwise.
equal ~cmp m1 m2
tests whether the maps m1
and m2
are equal, that is, contain equal keys and associate them with equal data. cmp
is the equality predicate used to compare the data associated with the keys.
Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps.
for_all ~f m
checks if all the bindings of the map satisfy the predicate f
.
exists ~f m
checks if at least one binding of the map satisfies the predicate f
.
of_list bs
adds the bindings of bs
to the empty map, in list order (if a key is bound twice in bs
the last one takes over).
Iterate on the whole map, in descending order of keys
to_seq_from k m
iterates on a subset of the bindings of m
, in ascending order of keys, from key k
or above.
MoreLabels.Map
Association tables over ordered types.
This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map.
For instance:
module IntPairs =
+ struct
+ type t = int * int
+ let compare (x0,y0) (x1,y1) =
+ match Stdlib.compare x0 x1 with
+ 0 -> Stdlib.compare y0 y1
+ | c -> c
+ end
+
+module PairsMap = Map.Make(IntPairs)
+
+let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world")
This creates a new module PairsMap
, with a new type 'a PairsMap.t
of maps from int * int
to 'a
. In this example, m
contains string
values so its type is string PairsMap.t
.
module type OrderedType = sig ... end
Input signature of the functor Make
.
Map.OrderedType
Input signature of the functor Make
.
A total ordering function over the keys. This is a two-argument function f
such that f e1 e2
is zero if the keys e1
and e2
are equal, f e1 e2
is strictly negative if e1
is smaller than e2
, and f e1 e2
is strictly positive if e1
is greater than e2
. Example: a suitable ordering function is the generic structural comparison function Stdlib.compare
.
Map.S
Output signature of the functor Make
.
val empty : 'a t
The empty map.
add ~key ~data m
returns a map containing the same bindings as m
, plus a binding of key
to data
. If key
was already bound in m
to a value that is physically equal to data
, m
is returned unchanged (the result of the function is then physically equal to m
). Otherwise, the previous binding of key
in m
disappears.
add_to_list ~key ~data m
is m
with key
mapped to l
such that l
is data :: Map.find key m
if key
was bound in m
and [v]
otherwise.
update ~key ~f m
returns a map containing the same bindings as m
, except for the binding of key
. Depending on the value of y
where y
is f (find_opt key m)
, the binding of key
is added, removed or updated. If y
is None
, the binding is removed if it exists; otherwise, if y
is Some z
then key
is associated to z
in the resulting map. If key
was already bound in m
to a value that is physically equal to z
, m
is returned unchanged (the result of the function is then physically equal to m
).
singleton x y
returns the one-element map that contains a binding y
for x
.
remove x m
returns a map containing the same bindings as m
, except for x
which is unbound in the returned map. If x
was not in m
, m
is returned unchanged (the result of the function is then physically equal to m
).
merge ~f m1 m2
computes a map whose keys are a subset of the keys of m1
and of m2
. The presence of each such binding, and the corresponding value, is determined with the function f
. In terms of the find_opt
operation, we have find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)
for any key x
, provided that f x None None = None
.
union ~f m1 m2
computes a map whose keys are a subset of the keys of m1
and of m2
. When the same binding is defined in both arguments, the function f
is used to combine them. This is a special case of merge
: union f m1 m2
is equivalent to merge f' m1 m2
, where
f' _key None None = None
f' _key (Some v) None = Some v
f' _key None (Some v) = Some v
f' key (Some v1) (Some v2) = f key v1 v2
val cardinal : 'a t -> int
Return the number of bindings of a map.
Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering Ord.compare
, where Ord
is the argument given to Map.Make
.
Return the binding with the smallest key in a given map (with respect to the Ord.compare
ordering), or raise Not_found
if the map is empty.
Return the binding with the smallest key in the given map (with respect to the Ord.compare
ordering), or None
if the map is empty.
Same as min_binding
, but returns the binding with the largest key in the given map.
Same as min_binding_opt
, but returns the binding with the largest key in the given map.
Return one binding of the given map, or raise Not_found
if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
Return one binding of the given map, or None
if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
find x m
returns the current value of x
in m
, or raises Not_found
if no binding for x
exists.
find_opt x m
returns Some v
if the current value of x
in m
is v
, or None
if no binding for x
exists.
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.
For example, find_first (fun k -> Ord.compare k x >= 0) m
will return the first binding k, v
of m
where Ord.compare k x >= 0
(intuitively: k >= x
), or raise Not_found
if x
is greater than any element of m
.
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.
find_last ~f m
, where f
is a monotonically decreasing function, returns the binding of m
with the highest key k
such that f k
, or raises Not_found
if no such key exists.
find_last_opt ~f m
, where f
is a monotonically decreasing function, returns an option containing the binding of m
with the highest key k
such that f k
, or None
if no such key exists.
iter ~f m
applies f
to all bindings in map m
. f
receives the key as first argument, and the associated value as second argument. The bindings are passed to f
in increasing order with respect to the ordering over the type of the keys.
fold ~f m ~init
computes (f kN dN ... (f k1 d1 init)...)
, where k1 ... kN
are the keys of all bindings in m
(in increasing order), and d1 ... dN
are the associated data.
map ~f m
returns a map with same domain as m
, where the associated value a
of all bindings of m
has been replaced by the result of the application of f
to a
. The bindings are passed to f
in increasing order with respect to the ordering over the type of the keys.
Same as map
, but the function receives as arguments both the key and the associated value for each binding of the map.
filter ~f m
returns the map with all the bindings in m
that satisfy predicate p
. If every binding in m
satisfies f
, m
is returned unchanged (the result of the function is then physically equal to m
)
filter_map ~f m
applies the function f
to every binding of m
, and builds a map from the results. For each binding (k, v)
in the input map:
f k v
is None
then k
is not in the result,f k v
is Some v'
then the binding (k, v')
is in the output map.For example, the following function on maps whose values are lists
filter_map
+ (fun _k li -> match li with [] -> None | _::tl -> Some tl)
+ m
drops all bindings of m
whose value is an empty list, and pops the first element of each value that is non-empty.
partition ~f m
returns a pair of maps (m1, m2)
, where m1
contains all the bindings of m
that satisfy the predicate f
, and m2
is the map with all the bindings of m
that do not satisfy f
.
split x m
returns a triple (l, data, r)
, where l
is the map with all the bindings of m
whose key is strictly less than x
; r
is the map with all the bindings of m
whose key is strictly greater than x
; data
is None
if m
contains no binding for x
, or Some v
if m
binds v
to x
.
val is_empty : 'a t -> bool
Test whether a map is empty or not.
mem x m
returns true
if m
contains a binding for x
, and false
otherwise.
equal ~cmp m1 m2
tests whether the maps m1
and m2
are equal, that is, contain equal keys and associate them with equal data. cmp
is the equality predicate used to compare the data associated with the keys.
Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps.
for_all ~f m
checks if all the bindings of the map satisfy the predicate f
.
exists ~f m
checks if at least one binding of the map satisfies the predicate f
.
of_list bs
adds the bindings of bs
to the empty map, in list order (if a key is bound twice in bs
the last one takes over).
Iterate on the whole map, in descending order of keys
to_seq_from k m
iterates on a subset of the bindings of m
, in ascending order of keys, from key k
or above.
Make.Ord
A total ordering function over the set elements. This is a two-argument function f
such that f e1 e2
is zero if the elements e1
and e2
are equal, f e1 e2
is strictly negative if e1
is smaller than e2
, and f e1 e2
is strictly positive if e1
is greater than e2
. Example: a suitable ordering function is the generic structural comparison function Stdlib.compare
.
Set.Make
Functor building an implementation of the set structure given a totally ordered type.
module Ord : OrderedType
type elt = Ord.t
The type of the set elements.
val empty : t
The empty set.
add x s
returns a set containing all elements of s
, plus x
. If x
was already in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
remove x s
returns a set containing all elements of s
, except x
. If x
was not in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
val cardinal : t -> int
Return the number of elements of a set.
Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering Ord.compare
, where Ord
is the argument given to Set.Make
.
Return the smallest element of the given set (with respect to the Ord.compare
ordering), or raise Not_found
if the set is empty.
Return the smallest element of the given set (with respect to the Ord.compare
ordering), or None
if the set is empty.
Same as min_elt_opt
, but returns the largest element of the given set.
Return one element of the given set, or raise Not_found
if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
Return one element of the given set, or None
if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
find x s
returns the element of s
equal to x
(according to Ord.compare
), or raise Not_found
if no such element exists.
find_opt x s
returns the element of s
equal to x
(according to Ord.compare
), or None
if no such element exists.
find_first ~f s
, where f
is a monotonically increasing function, returns the lowest element e
of s
such that f e
, or raises Not_found
if no such element exists.
For example, find_first (fun e -> Ord.compare e x >= 0) s
will return the first element e
of s
where Ord.compare e x >= 0
(intuitively: e >= x
), or raise Not_found
if x
is greater than any element of s
.
find_first_opt ~f s
, where f
is a monotonically increasing function, returns an option containing the lowest element e
of s
such that f e
, or None
if no such element exists.
find_last ~f s
, where f
is a monotonically decreasing function, returns the highest element e
of s
such that f e
, or raises Not_found
if no such element exists.
find_last_opt ~f s
, where f
is a monotonically decreasing function, returns an option containing the highest element e
of s
such that f e
, or None
if no such element exists.
iter ~f s
applies f
in turn to all elements of s
. The elements of s
are presented to f
in increasing order with respect to the ordering over the type of the elements.
fold ~f s init
computes (f xN ... (f x2 (f x1 init))...)
, where x1 ... xN
are the elements of s
, in increasing order.
map ~f s
is the set whose elements are f a0
,f a1
... f
+ aN
, where a0
,a1
...aN
are the elements of s
.
The elements are passed to f
in increasing order with respect to the ordering over the type of the elements.
If no element of s
is changed by f
, s
is returned unchanged. (If each output of f
is physically equal to its input, the returned set is physically equal to s
.)
filter ~f s
returns the set of all elements in s
that satisfy predicate f
. If f
satisfies every element in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
filter_map ~f s
returns the set of all v
such that f x = Some v
for some element x
of s
.
For example,
filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s
is the set of halves of the even elements of s
.
If no element of s
is changed or dropped by f
(if f x = Some x
for each element x
), then s
is returned unchanged: the result of the function is then physically equal to s
.
partition ~f s
returns a pair of sets (s1, s2)
, where s1
is the set of all the elements of s
that satisfy the predicate f
, and s2
is the set of all the elements of s
that do not satisfy f
.
split x s
returns a triple (l, present, r)
, where l
is the set of elements of s
that are strictly less than x
; r
is the set of elements of s
that are strictly greater than x
; present
is false
if s
contains no element equal to x
, or true
if s
contains an element equal to x
.
val is_empty : t -> bool
Test whether a set is empty or not.
equal s1 s2
tests whether the sets s1
and s2
are equal, that is, contain equal elements.
Total ordering between sets. Can be used as the ordering function for doing sets of sets.
for_all ~f s
checks if all elements of the set satisfy the predicate f
.
exists ~f s
checks if at least one element of the set satisfies the predicate f
.
of_list l
creates a set from a list of elements. This is usually more efficient than folding add
over the list, except perhaps for lists with many duplicated elements.
to_seq_from x s
iterates on a subset of the elements of s
in ascending order, from x
or above.
MoreLabels.Set
Sets over ordered types.
This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance.
The Make
functor constructs implementations for any type, given a compare
function. For instance:
module IntPairs =
+ struct
+ type t = int * int
+ let compare (x0,y0) (x1,y1) =
+ match Stdlib.compare x0 x1 with
+ 0 -> Stdlib.compare y0 y1
+ | c -> c
+ end
+
+module PairsSet = Set.Make(IntPairs)
+
+let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13))
This creates a new module PairsSet
, with a new type PairsSet.t
of sets of int * int
.
module type OrderedType = sig ... end
Input signature of the functor Make
.
Set.OrderedType
Input signature of the functor Make
.
A total ordering function over the set elements. This is a two-argument function f
such that f e1 e2
is zero if the elements e1
and e2
are equal, f e1 e2
is strictly negative if e1
is smaller than e2
, and f e1 e2
is strictly positive if e1
is greater than e2
. Example: a suitable ordering function is the generic structural comparison function Stdlib.compare
.
Set.S
Output signature of the functor Make
.
val empty : t
The empty set.
add x s
returns a set containing all elements of s
, plus x
. If x
was already in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
remove x s
returns a set containing all elements of s
, except x
. If x
was not in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
val cardinal : t -> int
Return the number of elements of a set.
Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering Ord.compare
, where Ord
is the argument given to Set.Make
.
Return the smallest element of the given set (with respect to the Ord.compare
ordering), or raise Not_found
if the set is empty.
Return the smallest element of the given set (with respect to the Ord.compare
ordering), or None
if the set is empty.
Same as min_elt_opt
, but returns the largest element of the given set.
Return one element of the given set, or raise Not_found
if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
Return one element of the given set, or None
if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
find x s
returns the element of s
equal to x
(according to Ord.compare
), or raise Not_found
if no such element exists.
find_opt x s
returns the element of s
equal to x
(according to Ord.compare
), or None
if no such element exists.
find_first ~f s
, where f
is a monotonically increasing function, returns the lowest element e
of s
such that f e
, or raises Not_found
if no such element exists.
For example, find_first (fun e -> Ord.compare e x >= 0) s
will return the first element e
of s
where Ord.compare e x >= 0
(intuitively: e >= x
), or raise Not_found
if x
is greater than any element of s
.
find_first_opt ~f s
, where f
is a monotonically increasing function, returns an option containing the lowest element e
of s
such that f e
, or None
if no such element exists.
find_last ~f s
, where f
is a monotonically decreasing function, returns the highest element e
of s
such that f e
, or raises Not_found
if no such element exists.
find_last_opt ~f s
, where f
is a monotonically decreasing function, returns an option containing the highest element e
of s
such that f e
, or None
if no such element exists.
iter ~f s
applies f
in turn to all elements of s
. The elements of s
are presented to f
in increasing order with respect to the ordering over the type of the elements.
fold ~f s init
computes (f xN ... (f x2 (f x1 init))...)
, where x1 ... xN
are the elements of s
, in increasing order.
map ~f s
is the set whose elements are f a0
,f a1
... f
+ aN
, where a0
,a1
...aN
are the elements of s
.
The elements are passed to f
in increasing order with respect to the ordering over the type of the elements.
If no element of s
is changed by f
, s
is returned unchanged. (If each output of f
is physically equal to its input, the returned set is physically equal to s
.)
filter ~f s
returns the set of all elements in s
that satisfy predicate f
. If f
satisfies every element in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
filter_map ~f s
returns the set of all v
such that f x = Some v
for some element x
of s
.
For example,
filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s
is the set of halves of the even elements of s
.
If no element of s
is changed or dropped by f
(if f x = Some x
for each element x
), then s
is returned unchanged: the result of the function is then physically equal to s
.
partition ~f s
returns a pair of sets (s1, s2)
, where s1
is the set of all the elements of s
that satisfy the predicate f
, and s2
is the set of all the elements of s
that do not satisfy f
.
split x s
returns a triple (l, present, r)
, where l
is the set of elements of s
that are strictly less than x
; r
is the set of elements of s
that are strictly greater than x
; present
is false
if s
contains no element equal to x
, or true
if s
contains an element equal to x
.
val is_empty : t -> bool
Test whether a set is empty or not.
equal s1 s2
tests whether the sets s1
and s2
are equal, that is, contain equal elements.
Total ordering between sets. Can be used as the ordering function for doing sets of sets.
for_all ~f s
checks if all elements of the set satisfy the predicate f
.
exists ~f s
checks if at least one element of the set satisfies the predicate f
.
of_list l
creates a set from a list of elements. This is usually more efficient than folding add
over the list, except perhaps for lists with many duplicated elements.
to_seq_from x s
iterates on a subset of the elements of s
in ascending order, from x
or above.
Stdlib_alerting.MoreLabels
Printexc.Slot
type t = backtrace_slot
val is_raise : t -> bool
is_raise slot
is true
when slot
refers to a raising point in the code, and false
when it comes from a simple function call.
val is_inline : t -> bool
is_inline slot
is true
when slot
refers to a call that got inlined by the compiler, and false
when it comes from any other context.
location slot
returns the location information of the slot, if available, and None
otherwise.
Some possible reasons for failing to return a location are as follow:
-g
)val name : t -> string option
name slot
returns the name of the function or definition enclosing the location referred to by the slot.
name slot
returns None if the name is unavailable, which may happen for the same reasons as location
returning None.
val format : int -> t -> string option
format pos slot
returns the string representation of slot
as raw_backtrace_to_string
would format it, assuming it is the pos
-th element of the backtrace: the 0
-th element is pretty-printed differently than the others.
Whole-backtrace printing functions also skip some uninformative slots; in that case, format pos slot
returns None
.
Stdlib_alerting.Printexc
include sig ... end
Printexc.to_string_default e
returns a string representation of the exception e
, ignoring all registered exception printers.
Printexc.to_string e
returns a string representation of the exception e
.
Printexc.print fn x
applies fn
to x
and returns the result. If the evaluation of fn x
raises any exception, the name of the exception is printed on standard error output, and the exception is raised again. The typical use is to catch and report exceptions that escape a function application.
Printexc.catch fn x
is similar to Printexc.print
, but aborts the program with exit code 2 after printing the uncaught exception. This function is deprecated: the runtime system is now able to print uncaught exceptions as precisely as Printexc.catch
does. Moreover, calling Printexc.catch
makes it harder to track the location of the exception using the debugger or the stack backtrace facility. So, do not use Printexc.catch
in new code.
Printexc.print_backtrace oc
prints an exception backtrace on the output channel oc
. The backtrace lists the program locations where the most-recently raised exception was raised and where it was propagated through function calls.
If the call is not inside an exception handler, the returned backtrace is unspecified. If the call is after some exception-catching code (before in the handler, or in a when-guard during the matching of the exception handler), the backtrace may correspond to a later exception than the handled one.
Printexc.get_backtrace ()
returns a string containing the same exception backtrace that Printexc.print_backtrace
would print. Same restriction usage than print_backtrace
.
Printexc.record_backtrace b
turns recording of exception backtraces on (if b = true
) or off (if b = false
). Initially, backtraces are not recorded, unless the b
flag is given to the program through the OCAMLRUNPARAM
variable.
Printexc.backtrace_status()
returns true
if exception backtraces are currently recorded, false
if not.
Printexc.register_printer fn
registers fn
as an exception printer. The printer should return None
or raise an exception if it does not know how to convert the passed exception, and Some
+ s
with s
the resulting string if it can convert the passed exception. Exceptions raised by the printer are ignored.
When converting an exception into a string, the printers will be invoked in the reverse order of their registrations, until a printer returns a Some s
value (if no such printer exists, the runtime will use a generic printer).
When using this mechanism, one should be aware that an exception backtrace is attached to the thread that saw it raised, rather than to the exception itself. Practically, it means that the code related to fn
should not use the backtrace if it has itself raised an exception before.
Printexc.use_printers e
returns None
if there are no registered printers and Some s
with else as the resulting string otherwise.
The type raw_backtrace
stores a backtrace in a low-level format, which can be converted to usable form using raw_backtrace_entries
and backtrace_slots_of_raw_entry
below.
Converting backtraces to backtrace_slot
s is slower than capturing the backtraces. If an application processes many backtraces, it can be useful to use raw_backtrace
to avoid or delay conversion.
Raw backtraces cannot be marshalled. If you need marshalling, you should use the array returned by the backtrace_slots
function of the next section.
A raw_backtrace_entry
is an element of a raw_backtrace
.
Each raw_backtrace_entry
is an opaque integer, whose value is not stable between different programs, or even between different runs of the same binary.
A raw_backtrace_entry
can be converted to a usable form using backtrace_slots_of_raw_entry
below. Note that, due to inlining, a single raw_backtrace_entry
may convert to several backtrace_slot
s. Since the values of a raw_backtrace_entry
are not stable, they cannot be marshalled. If they are to be converted, the conversion must be done by the process that generated them.
Again due to inlining, there may be multiple distinct raw_backtrace_entry values that convert to equal backtrace_slot
s. However, if two raw_backtrace_entry
s are equal as integers, then they represent the same backtrace_slot
s.
val raw_backtrace_entries : raw_backtrace -> raw_backtrace_entry array
val get_raw_backtrace : unit -> raw_backtrace
Printexc.get_raw_backtrace ()
returns the same exception backtrace that Printexc.print_backtrace
would print, but in a raw format. Same restriction usage than print_backtrace
.
val print_raw_backtrace : Stdlib.out_channel -> raw_backtrace -> unit
Print a raw backtrace in the same format Printexc.print_backtrace
uses.
val raw_backtrace_to_string : raw_backtrace -> string
Return a string from a raw backtrace, in the same format Printexc.get_backtrace
uses.
val raise_with_backtrace : exn -> raw_backtrace -> 'a
Reraise the exception using the given raw_backtrace for the origin of the exception
val get_callstack : int -> raw_backtrace
Printexc.get_callstack n
returns a description of the top of the call stack on the current program point (for the current thread), with at most n
entries. (Note: this function is not related to exceptions at all, despite being part of the Printexc
module.)
val default_uncaught_exception_handler : exn -> raw_backtrace -> unit
Printexc.default_uncaught_exception_handler
prints the exception and backtrace on standard error output.
val set_uncaught_exception_handler : (exn -> raw_backtrace -> unit) -> unit
Printexc.set_uncaught_exception_handler fn
registers fn
as the handler for uncaught exceptions. The default handler is Printexc.default_uncaught_exception_handler
.
Note that when fn
is called all the functions registered with Stdlib.at_exit
have already been called. Because of this you must make sure any output channel fn
writes on is flushed.
Also note that exceptions raised by user code in the interactive toplevel are not passed to this function as they are caught by the toplevel itself.
If fn
raises an exception, both the exceptions passed to fn
and raised by fn
will be printed with their respective backtrace.
val backtrace_slots : raw_backtrace -> backtrace_slot array option
Returns the slots of a raw backtrace, or None
if none of them contain useful information.
In the return array, the slot at index 0
corresponds to the most recent function call, raise, or primitive get_backtrace
call in the trace.
Some possible reasons for returning None
are as follow:
-g
)ocamlc -g
)val backtrace_slots_of_raw_entry :
+ raw_backtrace_entry ->
+ backtrace_slot array option
Returns the slots of a single raw backtrace entry, or None
if this entry lacks debug information.
Slots are returned in the same order as backtrace_slots
: the slot at index 0
is the most recent call, raise, or primitive, and subsequent slots represent callers.
The type of location information found in backtraces. start_char
and end_char
are positions relative to the beginning of the line.
module Slot : sig ... end
This type is used to iterate over the slots of a raw_backtrace
. For most purposes, backtrace_slots_of_raw_entry
is easier to use.
Like raw_backtrace_entry
, values of this type are process-specific and must absolutely not be marshalled, and are unsafe to use for this reason (marshalling them may not fail, but un-marshalling and using the result will result in undefined behavior).
Elements of this type can still be compared and hashed: when two elements are equal, then they represent the same source location (the converse is not necessarily true in presence of inlining, for example).
val raw_backtrace_length : raw_backtrace -> int
raw_backtrace_length bckt
returns the number of slots in the backtrace bckt
.
val get_raw_backtrace_slot : raw_backtrace -> int -> raw_backtrace_slot
get_raw_backtrace_slot bckt pos
returns the slot in position pos
in the backtrace bckt
.
val convert_raw_backtrace_slot : raw_backtrace_slot -> backtrace_slot
Extracts the user-friendly backtrace_slot
from a low-level raw_backtrace_slot
.
val get_raw_backtrace_next_slot :
+ raw_backtrace_slot ->
+ raw_backtrace_slot option
get_raw_backtrace_next_slot slot
returns the next slot inlined, if any.
Sample code to iterate over all frames (inlined and non-inlined):
(* Iterate over inlined frames *)
+let rec iter_raw_backtrace_slot f slot =
+ f slot;
+ match get_raw_backtrace_next_slot slot with
+ | None -> ()
+ | Some slot' -> iter_raw_backtrace_slot f slot'
+
+(* Iterate over stack frames *)
+let iter_raw_backtrace f bt =
+ for i = 0 to raw_backtrace_length bt - 1 do
+ iter_raw_backtrace_slot f (get_raw_backtrace_slot bt i)
+ done
Printexc.exn_slot_id
returns an integer which uniquely identifies the constructor used to create the exception value exn
(in the current runtime).
Printexc.exn_slot_name exn
returns the internal name of the constructor used to create the exception value exn
.
Stdlib_alerting.Printf
include sig ... end
Same as Printf.fprintf
, but instead of printing on an output channel, return a string containing the result of formatting the arguments.
Same as sprintf
above, but instead of returning the string, passes it to the first argument.
fprintf outchan format arg1 ... argN
formats the arguments arg1
to argN
according to the format string format
, and outputs the resulting string on the channel outchan
.
The format string is a character string which contains two types of objects: plain characters, which are simply copied to the output channel, and conversion specifications, each of which causes conversion and printing of arguments.
Conversion specifications have the following form:
% [flags] [width] [.precision] type
In short, a conversion specification consists in the %
character, followed by optional modifiers and a type which is made of one or two characters.
The types and their meanings are:
d
, i
: convert an integer argument to signed decimal. The flag #
adds underscores to large values for readability.u
, n
, l
, L
, or N
: convert an integer argument to unsigned decimal. Warning: n
, l
, L
, and N
are used for scanf
, and should not be used for printf
. The flag #
adds underscores to large values for readability.x
: convert an integer argument to unsigned hexadecimal, using lowercase letters. The flag #
adds a 0x
prefix to non zero values.X
: convert an integer argument to unsigned hexadecimal, using uppercase letters. The flag #
adds a 0X
prefix to non zero values.o
: convert an integer argument to unsigned octal. The flag #
adds a 0
prefix to non zero values.s
: insert a string argument.S
: convert a string argument to OCaml syntax (double quotes, escapes).c
: insert a character argument.C
: convert a character argument to OCaml syntax (single quotes, escapes).f
: convert a floating-point argument to decimal notation, in the style dddd.ddd
.F
: convert a floating-point argument to OCaml syntax (dddd.
or dddd.ddd
or d.ddd e+-dd
). Converts to hexadecimal with the #
flag (see h
).e
or E
: convert a floating-point argument to decimal notation, in the style d.ddd e+-dd
(mantissa and exponent).g
or G
: convert a floating-point argument to decimal notation, in style f
or e
, E
(whichever is more compact). Moreover, any trailing zeros are removed from the fractional part of the result and the decimal-point character is removed if there is no fractional part remaining.h
or H
: convert a floating-point argument to hexadecimal notation, in the style 0xh.hhhh p+-dd
(hexadecimal mantissa, exponent in decimal and denotes a power of 2).B
: convert a boolean argument to the string true
or false
b
: convert a boolean argument (deprecated; do not use in new programs).ld
, li
, lu
, lx
, lX
, lo
: convert an int32
argument to the format specified by the second letter (decimal, hexadecimal, etc).nd
, ni
, nu
, nx
, nX
, no
: convert a nativeint
argument to the format specified by the second letter.Ld
, Li
, Lu
, Lx
, LX
, Lo
: convert an int64
argument to the format specified by the second letter.a
: user-defined printer. Take two arguments and apply the first one to outchan
(the current output channel) and to the second argument. The first argument must therefore have type out_channel -> 'b -> unit
and the second 'b
. The output produced by the function is inserted in the output of fprintf
at the current point.t
: same as %a
, but take only one argument (with type out_channel -> unit
) and apply it to outchan
.\{ fmt %\}
: convert a format string argument to its type digest. The argument must have the same type as the internal format string fmt
.( fmt %)
: format string substitution. Take a format string argument and substitute it to the internal format string fmt
to print following arguments. The argument must have the same type as the internal format string fmt
.!
: take no argument and flush the output.%
: take no argument and output one %
character.\@
: take no argument and output one \@
character.,
: take no argument and output nothing: a no-op delimiter for conversion specifications.The optional flags
are:
-
: left-justify the output (default is right justification).0
: for numerical conversions, pad with zeroes instead of spaces.+
: for signed numerical conversions, prefix number with a +
sign if positive.#
: request an alternate formatting style for the integer types and the floating-point type F
.The optional width
is an integer indicating the minimal width of the result. For instance, %6d
prints an integer, prefixing it with spaces to fill at least 6 characters.
The optional precision
is a dot .
followed by an integer indicating how many digits follow the decimal point in the %f
, %e
, %E
, %h
, and %H
conversions or the maximum number of significant digits to appear for the %F
, %g
and %G
conversions. For instance, %.4f
prints a float
with 4 fractional digits.
The integer in a width
or precision
can also be specified as *
, in which case an extra integer argument is taken to specify the corresponding width
or precision
. This integer argument precedes immediately the argument to print. For instance, %.*f
prints a float
with as many fractional digits as the value of the argument given before the float.
Same as Printf.fprintf
, but output on stdout
.
Same as Printf.fprintf
, but output on stderr
.
Same as Printf.fprintf
, but does not print anything. Useful to ignore some material when conditionally printing.
val kfprintf :
+ (Stdlib.out_channel -> 'd) ->
+ Stdlib.out_channel ->
+ ('a, Stdlib.out_channel, unit, 'd) Stdlib.format4 ->
+ 'a
Same as fprintf
, but instead of returning immediately, passes the out channel to its first argument at the end of printing.
Same as kfprintf
above, but does not print anything. Useful to ignore some material when conditionally printing.
Same as Printf.fprintf
, but instead of printing on an output channel, append the formatted arguments to the given extensible buffer (see module Buffer
).
Same as Printf.bprintf
, but does not print anything. Useful to ignore some material when conditionally printing.
Scanf.Scanning
Stdlib_alerting.Scanf
module Scanning : sig ... end
include sig ... end
type ('a, 'b, 'c, 'd) scanner =
+ ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd, 'd) Stdlib.format6 ->
+ 'c
The type of formatted input scanners: ('a, 'b, 'c, 'd) scanner
is the type of a formatted input function that reads from some formatted input channel according to some format string; more precisely, if scan
is some formatted input function, then scan
+ ic fmt f
applies f
to all the arguments specified by format string fmt
, when scan
has read those arguments from the Scanning.in_channel
formatted input channel ic
.
For instance, the Scanf.scanf
function below has type ('a, 'b, 'c, 'd) scanner
, since it is a formatted input function that reads from Scanning.stdin
: scanf fmt f
applies f
to the arguments specified by fmt
, reading those arguments from Stdlib.stdin
as expected.
If the format fmt
has some %r
indications, the corresponding formatted input functions must be provided before receiver function f
. For instance, if read_elem
is an input function for values of type t
, then bscanf ic "%r;" read_elem f
reads a value v
of type t
followed by a ';'
character, and returns f v
.
type ('a, 'b, 'c, 'd) scanner_opt =
+ ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd option, 'd) Stdlib.format6 ->
+ 'c
When the input can not be read according to the format string specification, formatted input functions typically raise exception Scan_failure
.
val sscanf : string -> ('a, 'b, 'c, 'd) scanner
Same as Scanf.bscanf
, but reads from the given string.
val sscanf_opt : string -> ('a, 'b, 'c, 'd) scanner_opt
Same as Scanf.sscanf
, but returns None
in case of scanning failure.
val ksscanf :
+ string ->
+ (Scanning.in_channel -> exn -> 'd) ->
+ ('a, 'b, 'c, 'd) scanner
Same as Scanf.kscanf
but reads from the given string.
val sscanf_format :
+ string ->
+ ('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6 ->
+ (('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6 -> 'g) ->
+ 'g
Same as Scanf.bscanf_format
, but reads from the given string.
val format_from_string :
+ string ->
+ ('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6 ->
+ ('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6
format_from_string s fmt
converts a string argument to a format string, according to the given format string fmt
.
unescaped s
return a copy of s
with escape sequences (according to the lexical conventions of OCaml) replaced by their corresponding special characters. More precisely, Scanf.unescaped
has the following property: for all string s
, Scanf.unescaped (String.escaped s) = s
.
Always return a copy of the argument, even if there is no escape sequence in the argument.
val bscanf : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner
val bscanf_opt : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner_opt
Same as Scanf.bscanf
, but returns None
in case of scanning failure.
val scanf : ('a, 'b, 'c, 'd) scanner
Same as Scanf.bscanf
, but reads from the predefined formatted input channel Scanf.Scanning.stdin
that is connected to Stdlib.stdin
.
val scanf_opt : ('a, 'b, 'c, 'd) scanner_opt
Same as Scanf.scanf
, but returns None
in case of scanning failure.
val kscanf :
+ Scanning.in_channel ->
+ (Scanning.in_channel -> exn -> 'd) ->
+ ('a, 'b, 'c, 'd) scanner
Same as Scanf.bscanf
, but takes an additional function argument ef
that is called in case of error: if the scanning process or some conversion fails, the scanning function aborts and calls the error handling function ef
with the formatted input channel and the exception that aborted the scanning process as arguments.
val bscanf_format :
+ Scanning.in_channel ->
+ ('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6 ->
+ (('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6 -> 'g) ->
+ 'g
bscanf_format ic fmt f
reads a format string token from the formatted input channel ic
, according to the given format string fmt
, and applies f
to the resulting format string value.
Stdlib_alerting.Seq
include sig ... end
type 'a t = unit -> 'a node
A sequence xs
of type 'a t
is a delayed list of elements of type 'a
. Such a sequence is queried by performing a function application xs()
. This function application returns a node, allowing the caller to determine whether the sequence is empty or nonempty, and in the latter case, to obtain its head and tail.
A node is either Nil
, which means that the sequence is empty, or Cons (x, xs)
, which means that x
is the first element of the sequence and that xs
is the remainder of the sequence.
val is_empty : 'a t -> bool
is_empty xs
determines whether the sequence xs
is empty.
It is recommended that the sequence xs
be persistent. Indeed, is_empty xs
demands the head of the sequence xs
, so, if xs
is ephemeral, it may be the case that xs
cannot be used any more after this call has taken place.
If xs
is empty, then uncons xs
is None
.
If xs
is nonempty, then uncons xs
is Some (x, ys)
where x
is the head of the sequence and ys
its tail.
val length : 'a t -> int
length xs
is the length of the sequence xs
.
The sequence xs
must be finite.
val iter : ('a -> unit) -> 'a t -> unit
iter f xs
invokes f x
successively for every element x
of the sequence xs
, from left to right.
It terminates only if the sequence xs
is finite.
val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc
fold_left f _ xs
invokes f _ x
successively for every element x
of the sequence xs
, from left to right.
An accumulator of type 'a
is threaded through the calls to f
.
It terminates only if the sequence xs
is finite.
val iteri : (int -> 'a -> unit) -> 'a t -> unit
iteri f xs
invokes f i x
successively for every element x
located at index i
in the sequence xs
.
It terminates only if the sequence xs
is finite.
iteri f xs
is equivalent to iter (fun (i, x) -> f i x) (zip (ints 0) xs)
.
val fold_lefti : ('acc -> int -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc
fold_lefti f _ xs
invokes f _ i x
successively for every element x
located at index i
of the sequence xs
.
An accumulator of type 'b
is threaded through the calls to f
.
It terminates only if the sequence xs
is finite.
fold_lefti f accu xs
is equivalent to fold_left (fun accu (i, x) -> f accu i x) accu (zip (ints 0) xs)
.
val for_all : ('a -> bool) -> 'a t -> bool
for_all p xs
determines whether all elements x
of the sequence xs
satisfy p x
.
The sequence xs
must be finite.
val exists : ('a -> bool) -> 'a t -> bool
exists xs p
determines whether at least one element x
of the sequence xs
satisfies p x
.
The sequence xs
must be finite.
val find : ('a -> bool) -> 'a t -> 'a option
find p xs
returns Some x
, where x
is the first element of the sequence xs
that satisfies p x
, if there is such an element.
It returns None
if there is no such element.
The sequence xs
must be finite.
val find_index : ('a -> bool) -> 'a t -> int option
find_index p xs
returns Some i
, where i
is the index of the first element of the sequence xs
that satisfies p x
, if there is such an element.
It returns None
if there is no such element.
The sequence xs
must be finite.
val find_map : ('a -> 'b option) -> 'a t -> 'b option
find_map f xs
returns Some y
, where x
is the first element of the sequence xs
such that f x = Some _
, if there is such an element, and where y
is defined by f x = Some y
.
It returns None
if there is no such element.
The sequence xs
must be finite.
val find_mapi : (int -> 'a -> 'b option) -> 'a t -> 'b option
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
The sequence xs
must be finite.
iter2 f xs ys
invokes f x y
successively for every pair (x, y)
of elements drawn synchronously from the sequences xs
and ys
.
If the sequences xs
and ys
have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
Iteration terminates only if at least one of the sequences xs
and ys
is finite.
iter2 f xs ys
is equivalent to iter (fun (x, y) -> f x y) (zip xs ys)
.
fold_left2 f _ xs ys
invokes f _ x y
successively for every pair (x, y)
of elements drawn synchronously from the sequences xs
and ys
.
An accumulator of type 'a
is threaded through the calls to f
.
If the sequences xs
and ys
have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
Iteration terminates only if at least one of the sequences xs
and ys
is finite.
fold_left2 f accu xs ys
is equivalent to fold_left (fun accu (x, y) -> f accu x y) (zip xs ys)
.
for_all2 p xs ys
determines whether all pairs (x, y)
of elements drawn synchronously from the sequences xs
and ys
satisfy p x y
.
If the sequences xs
and ys
have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. In particular, if xs
or ys
is empty, then for_all2 p xs ys
is true. This is where for_all2
and equal
differ: equal eq xs ys
can be true only if xs
and ys
have the same length.
At least one of the sequences xs
and ys
must be finite.
for_all2 p xs ys
is equivalent to for_all (fun b -> b) (map2 p xs ys)
.
exists2 p xs ys
determines whether some pair (x, y)
of elements drawn synchronously from the sequences xs
and ys
satisfies p x y
.
If the sequences xs
and ys
have different lengths, then iteration must stop as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
At least one of the sequences xs
and ys
must be finite.
exists2 p xs ys
is equivalent to exists (fun b -> b) (map2 p xs ys)
.
Provided the function eq
defines an equality on elements, equal eq xs ys
determines whether the sequences xs
and ys
are pointwise equal.
At least one of the sequences xs
and ys
must be finite.
Provided the function cmp
defines a preorder on elements, compare cmp xs ys
compares the sequences xs
and ys
according to the lexicographic preorder.
For more details on comparison functions, see Array.sort
.
At least one of the sequences xs
and ys
must be finite.
val empty : 'a t
empty
is the empty sequence. It has no elements. Its length is 0.
val return : 'a -> 'a t
return x
is the sequence whose sole element is x
. Its length is 1.
cons x xs
is the sequence that begins with the element x
, followed with the sequence xs
.
Writing cons (f()) xs
causes the function call f()
to take place immediately. For this call to be delayed until the sequence is queried, one must instead write (fun () -> Cons(f(), xs))
.
val init : int -> (int -> 'a) -> 'a t
init n f
is the sequence f 0; f 1; ...; f (n-1)
.
n
must be nonnegative.
If desired, the infinite sequence f 0; f 1; ...
can be defined as map f (ints 0)
.
val unfold : ('b -> ('a * 'b) option) -> 'b -> 'a t
unfold
constructs a sequence out of a step function and an initial state.
If f u
is None
then unfold f u
is the empty sequence. If f u
is Some (x, u')
then unfold f u
is the nonempty sequence cons x (unfold f u')
.
For example, unfold (function [] -> None | h :: t -> Some (h, t)) l
is equivalent to List.to_seq l
.
val repeat : 'a -> 'a t
repeat x
is the infinite sequence where the element x
is repeated indefinitely.
repeat x
is equivalent to cycle (return x)
.
val forever : (unit -> 'a) -> 'a t
forever f
is an infinite sequence where every element is produced (on demand) by the function call f()
.
For instance, forever Random.bool
is an infinite sequence of random bits.
forever f
is equivalent to map f (repeat ())
.
cycle xs
is the infinite sequence that consists of an infinite number of repetitions of the sequence xs
.
If xs
is an empty sequence, then cycle xs
is empty as well.
Consuming (a prefix of) the sequence cycle xs
once can cause the sequence xs
to be consumed more than once. Therefore, xs
must be persistent.
val iterate : ('a -> 'a) -> 'a -> 'a t
iterate f x
is the infinite sequence whose elements are x
, f x
, f (f x)
, and so on.
In other words, it is the orbit of the function f
, starting at x
.
map f xs
is the image of the sequence xs
through the transformation f
.
If xs
is the sequence x0; x1; ...
then map f xs
is the sequence f x0; f x1; ...
.
mapi
is analogous to map
, but applies the function f
to an index and an element.
mapi f xs
is equivalent to map2 f (ints 0) xs
.
filter p xs
is the sequence of the elements x
of xs
that satisfy p x
.
In other words, filter p xs
is the sequence xs
, deprived of the elements x
such that p x
is false.
filter_map f xs
is the sequence of the elements y
such that f x = Some y
, where x
ranges over xs
.
filter_map f xs
is equivalent to map Option.get (filter Option.is_some (map f xs))
.
If xs
is a sequence [x0; x1; x2; ...]
, then scan f a0 xs
is a sequence of accumulators [a0; a1; a2; ...]
where a1
is f a0 x0
, a2
is f a1 x1
, and so on.
Thus, scan f a0 xs
is conceptually related to fold_left f a0 xs
. However, instead of performing an eager iteration and immediately returning the final accumulator, it returns a sequence of accumulators.
For instance, scan (+) 0
transforms a sequence of integers into the sequence of its partial sums.
If xs
has length n
then scan f a0 xs
has length n+1
.
take n xs
is the sequence of the first n
elements of xs
.
If xs
has fewer than n
elements, then take n xs
is equivalent to xs
.
n
must be nonnegative.
drop n xs
is the sequence xs
, deprived of its first n
elements.
If xs
has fewer than n
elements, then drop n xs
is empty.
n
must be nonnegative.
drop
is lazy: the first n+1
elements of the sequence xs
are demanded only when the first element of drop n xs
is demanded. For this reason, drop 1 xs
is not equivalent to tail xs
, which queries xs
immediately.
take_while p xs
is the longest prefix of the sequence xs
where every element x
satisfies p x
.
drop_while p xs
is the sequence xs
, deprived of the prefix take_while p xs
.
Provided the function eq
defines an equality on elements, group eq xs
is the sequence of the maximal runs of adjacent duplicate elements of the sequence xs
.
Every element of group eq xs
is a nonempty sequence of equal elements.
The concatenation concat (group eq xs)
is equal to xs
.
Consuming group eq xs
, and consuming the sequences that it contains, can cause xs
to be consumed more than once. Therefore, xs
must be persistent.
The sequence memoize xs
has the same elements as the sequence xs
.
Regardless of whether xs
is ephemeral or persistent, memoize xs
is persistent: even if it is queried several times, xs
is queried at most once.
The construction of the sequence memoize xs
internally relies on suspensions provided by the module Lazy
. These suspensions are not thread-safe. Therefore, the sequence memoize xs
must not be queried by multiple threads concurrently.
If xss
is a matrix (a sequence of rows), then transpose xss
is the sequence of the columns of the matrix xss
.
The rows of the matrix xss
are not required to have the same length.
The matrix xss
is not required to be finite (in either direction).
The matrix xss
must be persistent.
append xs ys
is the concatenation of the sequences xs
and ys
.
Its elements are the elements of xs
, followed by the elements of ys
.
If xss
is a sequence of sequences, then concat xss
is its concatenation.
If xss
is the sequence xs0; xs1; ...
then concat xss
is the sequence xs0 @ xs1 @ ...
.
concat_map f xs
is equivalent to concat (map f xs)
.
concat_map
is an alias for flat_map
.
zip xs ys
is the sequence of pairs (x, y)
drawn synchronously from the sequences xs
and ys
.
If the sequences xs
and ys
have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
zip xs ys
is equivalent to map2 (fun a b -> (a, b)) xs ys
.
map2 f xs ys
is the sequence of the elements f x y
, where the pairs (x, y)
are drawn synchronously from the sequences xs
and ys
.
If the sequences xs
and ys
have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
map2 f xs ys
is equivalent to map (fun (x, y) -> f x y) (zip xs ys)
.
interleave xs ys
is the sequence that begins with the first element of xs
, continues with the first element of ys
, and so on.
When one of the sequences xs
and ys
is exhausted, interleave xs ys
continues with the rest of the other sequence.
If the sequences xs
and ys
are sorted according to the total preorder cmp
, then sorted_merge cmp xs ys
is the sorted sequence obtained by merging the sequences xs
and ys
.
For more details on comparison functions, see Array.sort
.
product xs ys
is the Cartesian product of the sequences xs
and ys
.
For every element x
of xs
and for every element y
of ys
, the pair (x, y)
appears once as an element of product xs ys
.
The order in which the pairs appear is unspecified.
The sequences xs
and ys
are not required to be finite.
The sequences xs
and ys
must be persistent.
The sequence map_product f xs ys
is the image through f
of the Cartesian product of the sequences xs
and ys
.
For every element x
of xs
and for every element y
of ys
, the element f x y
appears once as an element of map_product f xs ys
.
The order in which these elements appear is unspecified.
The sequences xs
and ys
are not required to be finite.
The sequences xs
and ys
must be persistent.
map_product f xs ys
is equivalent to map (fun (x, y) -> f x y) (product xs ys)
.
unzip
transforms a sequence of pairs into a pair of sequences.
unzip xs
is equivalent to (map fst xs, map snd xs)
.
Querying either of the sequences returned by unzip xs
causes xs
to be queried. Therefore, querying both of them causes xs
to be queried twice. Thus, xs
must be persistent and cheap. If that is not the case, use unzip (memoize xs)
.
partition_map f xs
returns a pair of sequences (ys, zs)
, where:
ys
is the sequence of the elements y
such that f x = Left y
, where x
ranges over xs
;zs
is the sequence of the elements z
such that f x = Right z
, where x
ranges over xs
.partition_map f xs
is equivalent to a pair of filter_map Either.find_left (map f xs)
and filter_map Either.find_right (map f xs)
.
Querying either of the sequences returned by partition_map f xs
causes xs
to be queried. Therefore, querying both of them causes xs
to be queried twice. Thus, xs
must be persistent and cheap. If that is not the case, use partition_map f (memoize xs)
.
partition p xs
returns a pair of the subsequence of the elements of xs
that satisfy p
and the subsequence of the elements of xs
that do not satisfy p
.
partition p xs
is equivalent to filter p xs, filter (fun x -> not (p x)) xs
.
Consuming both of the sequences returned by partition p xs
causes xs
to be consumed twice and causes the function f
to be applied twice to each element of the list. Therefore, f
should be pure and cheap. Furthermore, xs
should be persistent and cheap. If that is not the case, use partition p (memoize xs)
.
val of_dispenser : (unit -> 'a option) -> 'a t
of_dispenser it
is the sequence of the elements produced by the dispenser it
. It is an ephemeral sequence: it can be consumed at most once. If a persistent sequence is needed, use memoize (of_dispenser it)
.
val ints : int -> int t
ints i
is the infinite sequence of the integers beginning at i
and counting up.
The sequence once xs
has the same elements as the sequence xs
.
Regardless of whether xs
is ephemeral or persistent, once xs
is an ephemeral sequence: it can be queried at most once. If it (or a suffix of it) is queried more than once, then the exception Forced_twice
is raised. This can be useful, while debugging or testing, to ensure that a sequence is consumed at most once.
This exception is raised when a sequence returned by once
(or a suffix of it) is queried more than once.
val to_dispenser : 'a t -> unit -> 'a option
to_dispenser xs
is a fresh dispenser on the sequence xs
.
This dispenser has mutable internal state, which is not protected by a lock; so, it must not be used by several threads concurrently.
StdLabels.List
include sig ... end
Compare the lengths of two lists. compare_lengths l1 l2
is equivalent to compare (length l1) (length l2)
, except that the computation stops after reaching the end of the shortest list.
Compare the length of a list to an integer. compare_length_with l len
is equivalent to compare (length l) len
, except that the computation stops after at most len
iterations on the list.
is_empty l
is true if and only if l
has no elements. It is equivalent to compare_length_with l 0 = 0
.
Return the n
-th element of the given list. The first element (head of the list) is at position 0.
Return the n
-th element of the given list. The first element (head of the list) is at position 0. Return None
if the list is too short.
init ~len ~f
is [f 0; f 1; ...; f (len-1)]
, evaluated left to right.
append l0 l1
appends l1
to l0
. Same function as the infix operator @
.
rev_append l1 l2
reverses l1
and concatenates it with l2
. This is equivalent to (
rev
l1) @ l2
.
Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument + length of the longest sub-list).
Same as concat
. Not tail-recursive (length of the argument + length of the longest sub-list).
equal eq [a1; ...; an] [b1; ..; bm]
holds when the two input lists have the same length, and for each pair of elements ai
, bi
at the same position we have eq ai bi
.
Note: the eq
function may be called even if the lists have different length. If you know your equality function is costly, you may want to check compare_lengths
first.
compare cmp [a1; ...; an] [b1; ...; bm]
performs a lexicographic comparison of the two input lists, using the same 'a -> 'a -> int
interface as Stdlib.compare
:
a1 :: l1
is smaller than a2 :: l2
(negative result) if a1
is smaller than a2
, or if they are equal (0 result) and l1
is smaller than l2
[]
is strictly smaller than non-empty listsNote: the cmp
function will be called even if the lists have different lengths.
iter ~f [a1; ...; an]
applies function f
in turn to [a1; ...; an]
. It is equivalent to f a1; f a2; ...; f an
.
Same as iter
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
map ~f [a1; ...; an]
applies function f
to a1, ..., an
, and builds the list [f a1; ...; f an]
with the results returned by f
.
Same as map
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
filter_map ~f l
applies f
to every element of l
, filters out the None
elements and returns the list of the arguments of the Some
elements.
fold_left_map
is a combination of fold_left
and map
that threads an accumulator through calls to f
.
fold_left ~f ~init [b1; ...; bn]
is f (... (f (f init b1) b2) ...) bn
.
fold_right ~f [a1; ...; an] ~init
is f a1 (f a2 (... (f an init) ...))
. Not tail-recursive.
iter2 ~f [a1; ...; an] [b1; ...; bn]
calls in turn f a1 b1; ...; f an bn
.
map2 ~f [a1; ...; an] [b1; ...; bn]
is [f a1 b1; ...; f an bn]
.
fold_left2 ~f ~init [a1; ...; an] [b1; ...; bn]
is f (... (f (f init a1 b1) a2 b2) ...) an bn
.
fold_right2 ~f [a1; ...; an] [b1; ...; bn] ~init
is f a1 b1 (f a2 b2 (... (f an bn init) ...))
.
for_all ~f [a1; ...; an]
checks if all elements of the list satisfy the predicate f
. That is, it returns (f a1) && (f a2) && ... && (f an)
for a non-empty list and true
if the list is empty.
exists ~f [a1; ...; an]
checks if at least one element of the list satisfies the predicate f
. That is, it returns (f a1) || (f a2) || ... || (f an)
for a non-empty list and false
if the list is empty.
Same as for_all
, but for a two-argument predicate.
Same as exists
, but for a two-argument predicate.
mem a ~set
is true if and only if a
is equal to an element of set
.
find ~f l
returns the first element of the list l
that satisfies the predicate f
.
find ~f l
returns the first element of the list l
that satisfies the predicate f
. Returns None
if there is no value that satisfies f
in the list l
.
find_index ~f xs
returns Some i
, where i
is the index of the first element of the list xs
that satisfies f x
, if there is such an element.
It returns None
if there is no such element.
find_map ~f l
applies f
to the elements of l
in order, and returns the first result of the form Some v
, or None
if none exist.
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
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 is preserved.
find_all
is another name for filter
.
Same as filter
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
partition ~f l
returns a pair of lists (l1, l2)
, where l1
is the list of all the elements of l
that satisfy the predicate f
, and l2
is the list of all the elements of l
that do not satisfy f
. The order of the elements in the input list is preserved.
partition_map f l
returns a pair of lists (l1, l2)
such that, for each element x
of the input list l
:
f x
is Left y1
, then y1
is in l1
, andf x
is Right y2
, then y2
is in l2
.The output elements are included in l1
and l2
in the same relative order as the corresponding input elements in l
.
In particular, partition_map (fun x -> if f x then Left x else Right x) l
is equivalent to partition f l
.
assoc a l
returns the value associated with key a
in the list of pairs l
. That is, assoc a [ ...; (a,b); ...] = b
if (a,b)
is the leftmost binding of a
in list l
.
assoc_opt a l
returns the value associated with key a
in the list of pairs l
. That is, assoc_opt a [ ...; (a,b); ...] = Some b
if (a,b)
is the leftmost binding of a
in list l
. Returns None
if there is no value associated with a
in the list l
.
Same as assoc
, but simply return true
if a binding exists, and false
if no bindings exist for the given key.
remove_assoc a l
returns the list of pairs l
without the first pair with key a
, if any. Not tail-recursive.
Transform a list of pairs into a pair of lists: split [(a1,b1); ...; (an,bn)]
is ([a1; ...; an], [b1; ...; bn])
. Not tail-recursive.
Transform a pair of lists into a list of pairs: combine [a1; ...; an] [b1; ...; bn]
is [(a1,b1); ...; (an,bn)]
.
Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, Stdlib.compare
is a suitable comparison function. The resulting list is sorted in increasing order. sort
is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space.
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
, but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order).
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
or stable_sort
, whichever is faster on typical input.
Same as sort
, but also remove duplicates.
Merge two lists: Assuming that l1
and l2
are sorted according to the comparison function cmp
, merge ~cmp l1 l2
will return a sorted list containing all the elements of l1
and l2
. If several elements compare equal, the elements of l1
will be before the elements of l2
. Not tail-recursive (sum of the lengths of the arguments).
Same as mem
, but uses physical equality instead of structural equality to compare list elements.
Same as assoc
, but uses physical equality instead of structural equality to compare keys.
Same as assoc_opt
, but uses physical equality instead of structural equality to compare keys.
Same as mem_assoc
, but uses physical equality instead of structural equality to compare keys.
Same as remove_assoc
, but uses physical equality instead of structural equality to compare keys. Not tail-recursive.
StdLabels.String
include sig ... end
make n c
is a string of length n
with each index holding the character c
.
init n ~f
is a string of length n
with index i
holding the character f i
(called in increasing index order).
get s i
is the character at index i
in s
. This is the same as writing s.[i]
.
concat ~sep ss
concatenates the list of strings ss
, inserting the separator string sep
between each.
compare s0 s1
sorts s0
and s1
in lexicographical order. compare
behaves like Stdlib.compare
on strings but may be more efficient.
starts_with
~prefix s
is true
if and only if s
starts with prefix
.
ends_with
~suffix s
is true
if and only if s
ends with suffix
.
contains_from s start c
is true
if and only if c
appears in s
after position start
.
rcontains_from s stop c
is true
if and only if c
appears in s
before position stop+1
.
contains s c
is String.contains_from
s 0 c
.
sub s ~pos ~len
is a string of length len
, containing the substring of s
that starts at position pos
and has length len
.
split_on_char ~sep s
is the list of all (possibly empty) substrings of s
that are delimited by the character sep
.
The function's result is specified by the following invariants:
sep
as a separator returns a string equal to the input (concat (make 1 sep)
+ (split_on_char sep s) = s
).sep
character.map f s
is the string resulting from applying f
to all the characters of s
in increasing order.
mapi ~f s
is like map
but the index of the character is also passed to f
.
fold_left f x s
computes f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]
, where n
is the length of the string s
.
fold_right f s x
computes f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))
, where n
is the length of the string s
.
for_all p s
checks if all characters in s
satisfy the predicate p
.
exists p s
checks if at least one character of s
satisfies the predicate p
.
trim s
is s
without leading and trailing whitespace. Whitespace characters are: ' '
, '\x0C'
(form feed), '\n'
, '\r'
, and '\t'
.
escaped s
is s
with special characters represented by escape sequences, following the lexical conventions of OCaml.
All characters outside the US-ASCII printable range [0x20;0x7E] are escaped, as well as backslash (0x2F) and double-quote (0x22).
The function Scanf.unescaped
is a left inverse of escaped
, i.e. Scanf.unescaped (escaped s) = s
for any string s
(unless escaped s
fails).
uppercase_ascii s
is s
with all lowercase letters translated to uppercase, using the US-ASCII character set.
lowercase_ascii s
is s
with all uppercase letters translated to lowercase, using the US-ASCII character set.
capitalize_ascii s
is s
with the first character set to uppercase, using the US-ASCII character set.
uncapitalize_ascii s
is s
with the first character set to lowercase, using the US-ASCII character set.
iter ~f s
applies function f
in turn to all the characters of s
. It is equivalent to f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()
.
iteri
is like iter
, but the function is also given the corresponding character index.
index_from s i c
is the index of the first occurrence of c
in s
after position i
.
index_from_opt s i c
is the index of the first occurrence of c
in s
after position i
(if any).
rindex_from s i c
is the index of the last occurrence of c
in s
before position i+1
.
rindex_from_opt s i c
is the index of the last occurrence of c
in s
before position i+1
(if any).
index s c
is String.index_from
s 0 c
.
index_opt s c
is String.index_from_opt
s 0 c
.
rindex s c
is String.rindex_from
s (length s - 1) c
.
rindex_opt s c
is String.rindex_from_opt
s (length s - 1) c
.
val to_seq : t -> char Stdlib.Seq.t
to_seq s
is a sequence made of the string's characters in increasing order. In "unsafe-string"
mode, modifications of the string during iteration will be reflected in the sequence.
val to_seqi : t -> (int * char) Stdlib.Seq.t
to_seqi s
is like to_seq
but also tuples the corresponding index.
val of_seq : char Stdlib.Seq.t -> t
of_seq s
is a string made of the sequence's characters.
val get_utf_8_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_8_uchar b i
decodes an UTF-8 character at index i
in b
.
val is_valid_utf_8 : t -> bool
is_valid_utf_8 b
is true
if and only if b
contains valid UTF-8 data.
val get_utf_16be_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16be_uchar b i
decodes an UTF-16BE character at index i
in b
.
val is_valid_utf_16be : t -> bool
is_valid_utf_16be b
is true
if and only if b
contains valid UTF-16BE data.
val get_utf_16le_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16le_uchar b i
decodes an UTF-16LE character at index i
in b
.
val is_valid_utf_16le : t -> bool
is_valid_utf_16le b
is true
if and only if b
contains valid UTF-16LE data.
get_uint8 b i
is b
's unsigned 8-bit integer starting at character index i
.
get_int8 b i
is b
's signed 8-bit integer starting at character index i
.
get_uint16_ne b i
is b
's native-endian unsigned 16-bit integer starting at character index i
.
get_uint16_be b i
is b
's big-endian unsigned 16-bit integer starting at character index i
.
get_uint16_le b i
is b
's little-endian unsigned 16-bit integer starting at character index i
.
get_int16_ne b i
is b
's native-endian signed 16-bit integer starting at character index i
.
get_int16_be b i
is b
's big-endian signed 16-bit integer starting at character index i
.
get_int16_le b i
is b
's little-endian signed 16-bit integer starting at character index i
.
get_int32_ne b i
is b
's native-endian 32-bit integer starting at character index i
.
val hash : t -> int
An unseeded hash function for strings, with the same output value as Hashtbl.hash
. This function allows this module to be passed as argument to the functor Hashtbl.Make
.
val seeded_hash : int -> t -> int
A seeded hash function for strings, with the same output value as Hashtbl.seeded_hash
. This function allows this module to be passed as argument to the functor Hashtbl.MakeSeeded
.
get_int32_be b i
is b
's big-endian 32-bit integer starting at character index i
.
get_int32_le b i
is b
's little-endian 32-bit integer starting at character index i
.
get_int64_ne b i
is b
's native-endian 64-bit integer starting at character index i
.
get_int64_be b i
is b
's big-endian 64-bit integer starting at character index i
.
get_int64_le b i
is b
's little-endian 64-bit integer starting at character index i
.
Return a new string that contains the same bytes as the given byte sequence.
Return a new byte sequence that contains the same bytes as the given string.
Stdlib_alerting.StdLabels
module String : StringLabels_alerting
module List : ListLabels_alerting
Stdlib_alerting.String
include sig ... end
make n c
is a string of length n
with each index holding the character c
.
init n f
is a string of length n
with index i
holding the character f i
(called in increasing index order).
get s i
is the character at index i
in s
. This is the same as writing s.[i]
.
concat sep ss
concatenates the list of strings ss
, inserting the separator string sep
between each.
compare s0 s1
sorts s0
and s1
in lexicographical order. compare
behaves like Stdlib.compare
on strings but may be more efficient.
starts_with
~prefix s
is true
if and only if s
starts with prefix
.
ends_with
~suffix s
is true
if and only if s
ends with suffix
.
contains_from s start c
is true
if and only if c
appears in s
after position start
.
rcontains_from s stop c
is true
if and only if c
appears in s
before position stop+1
.
contains s c
is String.contains_from
s 0 c
.
sub s pos len
is a string of length len
, containing the substring of s
that starts at position pos
and has length len
.
split_on_char sep s
is the list of all (possibly empty) substrings of s
that are delimited by the character sep
.
The function's result is specified by the following invariants:
sep
as a separator returns a string equal to the input (concat (make 1 sep)
+ (split_on_char sep s) = s
).sep
character.map f s
is the string resulting from applying f
to all the characters of s
in increasing order.
mapi f s
is like map
but the index of the character is also passed to f
.
fold_left f x s
computes f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]
, where n
is the length of the string s
.
fold_right f s x
computes f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))
, where n
is the length of the string s
.
for_all p s
checks if all characters in s
satisfy the predicate p
.
exists p s
checks if at least one character of s
satisfies the predicate p
.
trim s
is s
without leading and trailing whitespace. Whitespace characters are: ' '
, '\x0C'
(form feed), '\n'
, '\r'
, and '\t'
.
escaped s
is s
with special characters represented by escape sequences, following the lexical conventions of OCaml.
All characters outside the US-ASCII printable range [0x20;0x7E] are escaped, as well as backslash (0x2F) and double-quote (0x22).
The function Scanf.unescaped
is a left inverse of escaped
, i.e. Scanf.unescaped (escaped s) = s
for any string s
(unless escaped s
fails).
uppercase_ascii s
is s
with all lowercase letters translated to uppercase, using the US-ASCII character set.
lowercase_ascii s
is s
with all uppercase letters translated to lowercase, using the US-ASCII character set.
capitalize_ascii s
is s
with the first character set to uppercase, using the US-ASCII character set.
uncapitalize_ascii s
is s
with the first character set to lowercase, using the US-ASCII character set.
iter f s
applies function f
in turn to all the characters of s
. It is equivalent to f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()
.
iteri
is like iter
, but the function is also given the corresponding character index.
index_from s i c
is the index of the first occurrence of c
in s
after position i
.
index_from_opt s i c
is the index of the first occurrence of c
in s
after position i
(if any).
rindex_from s i c
is the index of the last occurrence of c
in s
before position i+1
.
rindex_from_opt s i c
is the index of the last occurrence of c
in s
before position i+1
(if any).
index s c
is String.index_from
s 0 c
.
index_opt s c
is String.index_from_opt
s 0 c
.
rindex s c
is String.rindex_from
s (length s - 1) c
.
rindex_opt s c
is String.rindex_from_opt
s (length s - 1) c
.
val to_seq : t -> char Stdlib.Seq.t
to_seq s
is a sequence made of the string's characters in increasing order. In "unsafe-string"
mode, modifications of the string during iteration will be reflected in the sequence.
val to_seqi : t -> (int * char) Stdlib.Seq.t
to_seqi s
is like to_seq
but also tuples the corresponding index.
val of_seq : char Stdlib.Seq.t -> t
of_seq s
is a string made of the sequence's characters.
val get_utf_8_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_8_uchar b i
decodes an UTF-8 character at index i
in b
.
val is_valid_utf_8 : t -> bool
is_valid_utf_8 b
is true
if and only if b
contains valid UTF-8 data.
val get_utf_16be_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16be_uchar b i
decodes an UTF-16BE character at index i
in b
.
val is_valid_utf_16be : t -> bool
is_valid_utf_16be b
is true
if and only if b
contains valid UTF-16BE data.
val get_utf_16le_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16le_uchar b i
decodes an UTF-16LE character at index i
in b
.
val is_valid_utf_16le : t -> bool
is_valid_utf_16le b
is true
if and only if b
contains valid UTF-16LE data.
get_uint8 b i
is b
's unsigned 8-bit integer starting at character index i
.
get_int8 b i
is b
's signed 8-bit integer starting at character index i
.
get_uint16_ne b i
is b
's native-endian unsigned 16-bit integer starting at character index i
.
get_uint16_be b i
is b
's big-endian unsigned 16-bit integer starting at character index i
.
get_uint16_le b i
is b
's little-endian unsigned 16-bit integer starting at character index i
.
get_int16_ne b i
is b
's native-endian signed 16-bit integer starting at character index i
.
get_int16_be b i
is b
's big-endian signed 16-bit integer starting at character index i
.
get_int16_le b i
is b
's little-endian signed 16-bit integer starting at character index i
.
get_int32_ne b i
is b
's native-endian 32-bit integer starting at character index i
.
val hash : t -> int
An unseeded hash function for strings, with the same output value as Hashtbl.hash
. This function allows this module to be passed as argument to the functor Hashtbl.Make
.
val seeded_hash : int -> t -> int
A seeded hash function for strings, with the same output value as Hashtbl.seeded_hash
. This function allows this module to be passed as argument to the functor Hashtbl.MakeSeeded
.
get_int32_be b i
is b
's big-endian 32-bit integer starting at character index i
.
get_int32_le b i
is b
's little-endian 32-bit integer starting at character index i
.
get_int64_ne b i
is b
's native-endian 64-bit integer starting at character index i
.
get_int64_be b i
is b
's big-endian 64-bit integer starting at character index i
.
get_int64_le b i
is b
's little-endian 64-bit integer starting at character index i
.
Return a new string that contains the same bytes as the given byte sequence.
Return a new byte sequence that contains the same bytes as the given string.
Stdlib_alerting.StringLabels
include sig ... end
make n c
is a string of length n
with each index holding the character c
.
init n ~f
is a string of length n
with index i
holding the character f i
(called in increasing index order).
get s i
is the character at index i
in s
. This is the same as writing s.[i]
.
concat ~sep ss
concatenates the list of strings ss
, inserting the separator string sep
between each.
compare s0 s1
sorts s0
and s1
in lexicographical order. compare
behaves like Stdlib.compare
on strings but may be more efficient.
starts_with
~prefix s
is true
if and only if s
starts with prefix
.
ends_with
~suffix s
is true
if and only if s
ends with suffix
.
contains_from s start c
is true
if and only if c
appears in s
after position start
.
rcontains_from s stop c
is true
if and only if c
appears in s
before position stop+1
.
contains s c
is String.contains_from
s 0 c
.
sub s ~pos ~len
is a string of length len
, containing the substring of s
that starts at position pos
and has length len
.
split_on_char ~sep s
is the list of all (possibly empty) substrings of s
that are delimited by the character sep
.
The function's result is specified by the following invariants:
sep
as a separator returns a string equal to the input (concat (make 1 sep)
+ (split_on_char sep s) = s
).sep
character.map f s
is the string resulting from applying f
to all the characters of s
in increasing order.
mapi ~f s
is like map
but the index of the character is also passed to f
.
fold_left f x s
computes f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]
, where n
is the length of the string s
.
fold_right f s x
computes f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))
, where n
is the length of the string s
.
for_all p s
checks if all characters in s
satisfy the predicate p
.
exists p s
checks if at least one character of s
satisfies the predicate p
.
trim s
is s
without leading and trailing whitespace. Whitespace characters are: ' '
, '\x0C'
(form feed), '\n'
, '\r'
, and '\t'
.
escaped s
is s
with special characters represented by escape sequences, following the lexical conventions of OCaml.
All characters outside the US-ASCII printable range [0x20;0x7E] are escaped, as well as backslash (0x2F) and double-quote (0x22).
The function Scanf.unescaped
is a left inverse of escaped
, i.e. Scanf.unescaped (escaped s) = s
for any string s
(unless escaped s
fails).
uppercase_ascii s
is s
with all lowercase letters translated to uppercase, using the US-ASCII character set.
lowercase_ascii s
is s
with all uppercase letters translated to lowercase, using the US-ASCII character set.
capitalize_ascii s
is s
with the first character set to uppercase, using the US-ASCII character set.
uncapitalize_ascii s
is s
with the first character set to lowercase, using the US-ASCII character set.
iter ~f s
applies function f
in turn to all the characters of s
. It is equivalent to f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()
.
iteri
is like iter
, but the function is also given the corresponding character index.
index_from s i c
is the index of the first occurrence of c
in s
after position i
.
index_from_opt s i c
is the index of the first occurrence of c
in s
after position i
(if any).
rindex_from s i c
is the index of the last occurrence of c
in s
before position i+1
.
rindex_from_opt s i c
is the index of the last occurrence of c
in s
before position i+1
(if any).
index s c
is String.index_from
s 0 c
.
index_opt s c
is String.index_from_opt
s 0 c
.
rindex s c
is String.rindex_from
s (length s - 1) c
.
rindex_opt s c
is String.rindex_from_opt
s (length s - 1) c
.
val to_seq : t -> char Stdlib.Seq.t
to_seq s
is a sequence made of the string's characters in increasing order. In "unsafe-string"
mode, modifications of the string during iteration will be reflected in the sequence.
val to_seqi : t -> (int * char) Stdlib.Seq.t
to_seqi s
is like to_seq
but also tuples the corresponding index.
val of_seq : char Stdlib.Seq.t -> t
of_seq s
is a string made of the sequence's characters.
val get_utf_8_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_8_uchar b i
decodes an UTF-8 character at index i
in b
.
val is_valid_utf_8 : t -> bool
is_valid_utf_8 b
is true
if and only if b
contains valid UTF-8 data.
val get_utf_16be_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16be_uchar b i
decodes an UTF-16BE character at index i
in b
.
val is_valid_utf_16be : t -> bool
is_valid_utf_16be b
is true
if and only if b
contains valid UTF-16BE data.
val get_utf_16le_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16le_uchar b i
decodes an UTF-16LE character at index i
in b
.
val is_valid_utf_16le : t -> bool
is_valid_utf_16le b
is true
if and only if b
contains valid UTF-16LE data.
get_uint8 b i
is b
's unsigned 8-bit integer starting at character index i
.
get_int8 b i
is b
's signed 8-bit integer starting at character index i
.
get_uint16_ne b i
is b
's native-endian unsigned 16-bit integer starting at character index i
.
get_uint16_be b i
is b
's big-endian unsigned 16-bit integer starting at character index i
.
get_uint16_le b i
is b
's little-endian unsigned 16-bit integer starting at character index i
.
get_int16_ne b i
is b
's native-endian signed 16-bit integer starting at character index i
.
get_int16_be b i
is b
's big-endian signed 16-bit integer starting at character index i
.
get_int16_le b i
is b
's little-endian signed 16-bit integer starting at character index i
.
get_int32_ne b i
is b
's native-endian 32-bit integer starting at character index i
.
val hash : t -> int
An unseeded hash function for strings, with the same output value as Hashtbl.hash
. This function allows this module to be passed as argument to the functor Hashtbl.Make
.
val seeded_hash : int -> t -> int
A seeded hash function for strings, with the same output value as Hashtbl.seeded_hash
. This function allows this module to be passed as argument to the functor Hashtbl.MakeSeeded
.
get_int32_be b i
is b
's big-endian 32-bit integer starting at character index i
.
get_int32_le b i
is b
's little-endian 32-bit integer starting at character index i
.
get_int64_ne b i
is b
's native-endian 64-bit integer starting at character index i
.
get_int64_be b i
is b
's big-endian 64-bit integer starting at character index i
.
get_int64_le b i
is b
's little-endian 64-bit integer starting at character index i
.
Return a new string that contains the same bytes as the given byte sequence.
Return a new byte sequence that contains the same bytes as the given string.
Stdlib_alerting.Uchar
include sig ... end
The type for Unicode characters.
A value of this type represents a Unicode scalar value which is an integer in the ranges 0x0000
...0xD7FF
or 0xE000
...0x10FFFF
.
val min : t
min
is U+0000.
val max : t
max
is U+10FFFF.
val bom : t
bom
is U+FEFF, the byte order mark (BOM) character.
val rep : t
rep
is U+FFFD, the replacement character.
is_valid n
is true
if and only if n
is a Unicode scalar value (i.e. in the ranges 0x0000
...0xD7FF
or 0xE000
...0x10FFFF
).
val of_int : int -> t
of_int i
is i
as a Unicode character.
val to_int : t -> int
to_int u
is u
as an integer.
val is_char : t -> bool
is_char u
is true
if and only if u
is a latin1 OCaml character.
val of_char : char -> t
of_char c
is c
as a Unicode character.
val to_char : t -> char
to_char u
is u
as an OCaml latin1 character.
val hash : t -> int
hash u
associates a non-negative integer to u
.
The type for UTF decode results. Values of this type represent the result of a Unicode Transformation Format decoding attempt.
val utf_decode_is_valid : utf_decode -> bool
utf_decode_is_valid d
is true
if and only if d
holds a valid decode.
val utf_decode_uchar : utf_decode -> t
utf_decode_uchar d
is the Unicode character decoded by d
if utf_decode_is_valid d
is true
and Uchar.rep
otherwise.
val utf_decode_length : utf_decode -> int
utf_decode_length d
is the number of elements from the source that were consumed by the decode d
. This is always strictly positive and smaller or equal to 4
. The kind of source elements depends on the actual decoder; for the decoders of the standard library this function always returns a length in bytes.
val utf_decode : int -> t -> utf_decode
utf_decode n u
is a valid UTF decode for u
that consumed n
elements from the source for decoding. n
must be positive and smaller or equal to 4
(this is not checked by the module).
val utf_decode_invalid : int -> utf_decode
utf_decode_invalid n
is an invalid UTF decode that consumed n
elements from the source to error. n
must be positive and smaller or equal to 4
(this is not checked by the module). The resulting decode has rep
as the decoded Unicode character.
val utf_8_byte_length : t -> int
utf_8_byte_length u
is the number of bytes needed to encode u
in UTF-8.
val utf_16_byte_length : t -> int
utf_16_byte_length u
is the number of bytes needed to encode u
in UTF-16.
Stdlib_alerts.Stdlib_alerting
Stdlib
, but with the above module type.
Derived from Stdlib
, but with items that can be restricted annotated with alerts.
Things that can be restricted are marked with an ⚠️ Alert. Not everything marked here is disabled by default though. See Stdlib_alerts
for the defaults.
raise
primitives and standard exceptionsinclude sig ... end
The Exit
exception is not raised by any library function. It is provided for use in your programs.
Exception raised when none of the cases of a pattern-matching apply. The arguments are the location of the match keyword in the source code (file name, line number, column number).
Exception raised when an assertion fails. The arguments are the location of the assert keyword in the source code (file name, line number, column number).
Exception raised by library functions to signal that the given arguments do not make sense. The string gives some information to the programmer. As a general rule, this exception should not be caught, it denotes a programming error and the code should be modified not to trigger it.
Exception raised by library functions to signal that they are undefined on the given arguments. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Failure _ instead).
Exception raised by the garbage collector when there is insufficient memory to complete the computation. (Not reliable for allocations on the minor heap.)
Exception raised by the bytecode interpreter when the evaluation stack reaches its maximal size. This often indicates infinite or excessively deep recursion in the user's program.
Before 4.10, it was not fully implemented by the native-code compiler.
Exception raised by the input/output functions to report an operating system error. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Sys_error _ instead).
Exception raised by input functions to signal that the end of file has been reached.
Exception raised by integer division and remainder operations when their second argument is zero.
A special case of Sys_error raised when no I/O is possible on a non-blocking I/O channel.
Not including the impure (==)
and (!=)
.
include sig ... end
e1 = e2
tests for structural equality of e1
and e2
. Mutable structures (e.g. references and arrays) are equal if and only if their current contents are structurally equal, even if the two mutable objects are not the same physical object. Equality between functional values raises Invalid_argument
. Equality between cyclic data structures may not terminate. Left-associative operator, see Ocaml_operators
for more information.
Negation of Stdlib.(=)
. Left-associative operator, see Ocaml_operators
for more information.
See Stdlib.(>=)
. Left-associative operator, see Ocaml_operators
for more information.
See Stdlib.(>=)
. Left-associative operator, see Ocaml_operators
for more information.
See Stdlib.(>=)
. Left-associative operator, see Ocaml_operators
for more information.
Structural ordering functions. These functions coincide with the usual orderings over integers, characters, strings, byte sequences and floating-point numbers, and extend them to a total ordering over all types. The ordering is compatible with ( = )
. As in the case of ( = )
, mutable structures are compared by contents. Comparison between functional values raises Invalid_argument
. Comparison between cyclic structures may not terminate. Left-associative operator, see Ocaml_operators
for more information.
compare x y
returns 0
if x
is equal to y
, a negative integer if x
is less than y
, and a positive integer if x
is greater than y
. The ordering implemented by compare
is compatible with the comparison predicates =
, <
and >
defined above, with one difference on the treatment of the float value Stdlib.nan
. Namely, the comparison predicates treat nan
as different from any other float value, including itself; while compare
treats nan
as equal to itself and less than any other float value. This treatment of nan
ensures that compare
defines a total ordering relation.
compare
applied to functional values may raise Invalid_argument
. compare
applied to cyclic structures may not terminate.
The compare
function can be used as the comparison function required by the Set.Make
and Map.Make
functors, as well as the List.sort
and Array.sort
functions.
Return the smaller of the two arguments. The result is unspecified if one of the arguments contains the float value nan
.
The impure (==)
and (!=)
include sig ... end
e1 == e2
tests for physical equality of e1
and e2
. On mutable types such as references, arrays, byte sequences, records with mutable fields and objects with mutable instance variables, e1 == e2
is true if and only if physical modification of e1
also affects e2
. On non-mutable types, the behavior of ( == )
is implementation-dependent; however, it is guaranteed that e1 == e2
implies compare e1 e2 = 0
. Left-associative operator, see Ocaml_operators
for more information.
include sig ... end
The boolean 'and'. Evaluation is sequential, left-to-right: in e1 && e2
, e1
is evaluated first, and if it returns false
, e2
is not evaluated at all. Right-associative operator, see Ocaml_operators
for more information.
These are safe in the sense that referential transparency is preserved, if two uses of a macro at separate locations are considered separate occurrences.
include sig ... end
__LOC__
returns the location at which this expression appears in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d".
__LINE__
returns the line number at which this expression appears in the file currently being parsed by the compiler.
__POS__
returns a tuple (file,lnum,cnum,enum)
, corresponding to the location at which this expression appears in the file currently being parsed by the compiler. file
is the current filename, lnum
the line number, cnum
the character position in the line and enum
the last character position in the line.
__FUNCTION__
returns the name of the current function or method, including any enclosing modules or classes.
__LOC_OF__ expr
returns a pair (loc, expr)
where loc
is the location of expr
in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d".
__LINE_OF__ expr
returns a pair (line, expr)
, where line
is the line number at which the expression expr
appears in the file currently being parsed by the compiler.
__POS_OF__ expr
returns a pair (loc,expr)
, where loc
is a tuple (file,lnum,cnum,enum)
corresponding to the location at which the expression expr
appears in the file currently being parsed by the compiler. file
is the current filename, lnum
the line number, cnum
the character position in the line and enum
the last character position in the line.
include sig ... end
Reverse-application operator: x |> f |> g
is exactly equivalent to g (f (x))
. Left-associative operator, see Ocaml_operators
for more information.
include sig ... end
Unary negation. You can also write - e
instead of ~- e
. Unary operator, see Ocaml_operators
for more information.
Unary addition. You can also write + e
instead of ~+ e
. Unary operator, see Ocaml_operators
for more information.
Integer addition. Left-associative operator, see Ocaml_operators
for more information.
Integer subtraction. Left-associative operator, , see Ocaml_operators
for more information.
Integer multiplication. Left-associative operator, see Ocaml_operators
for more information.
Integer division. Integer division rounds the real quotient of its arguments towards zero. More precisely, if x >= 0
and y > 0
, x / y
is the greatest integer less than or equal to the real quotient of x
by y
. Moreover, (- x) / y = x / (- y) = - (x / y)
. Left-associative operator, see Ocaml_operators
for more information.
Integer remainder. If y
is not zero, the result of x mod y
satisfies the following properties: x = (x / y) * y + x mod y
and abs(x mod y) <= abs(y) - 1
. If y = 0
, x mod y
raises Division_by_zero
. Note that x mod y
is negative only if x < 0
. Left-associative operator, see Ocaml_operators
for more information.
abs x
is the absolute value of x
. On min_int
this is min_int
itself and thus remains negative.
Bitwise logical and. Left-associative operator, see Ocaml_operators
for more information.
Bitwise logical or. Left-associative operator, see Ocaml_operators
for more information.
Bitwise logical exclusive or. Left-associative operator, see Ocaml_operators
for more information.
n lsl m
shifts n
to the left by m
bits. The result is unspecified if m < 0
or m > Sys.int_size
. Right-associative operator, see Ocaml_operators
for more information.
n lsr m
shifts n
to the right by m
bits. This is a logical shift: zeroes are inserted regardless of the sign of n
. The result is unspecified if m < 0
or m > Sys.int_size
. Right-associative operator, see Ocaml_operators
for more information.
n asr m
shifts n
to the right by m
bits. This is an arithmetic shift: the sign bit of n
is replicated. The result is unspecified if m < 0
or m > Sys.int_size
. Right-associative operator, see Ocaml_operators
for more information.
include sig ... end
Unary negation. You can also write -. e
instead of ~-. e
. Unary operator, see Ocaml_operators
for more information.
Unary addition. You can also write +. e
instead of ~+. e
. Unary operator, see Ocaml_operators
for more information.
Floating-point addition. Left-associative operator, see Ocaml_operators
for more information.
Floating-point subtraction. Left-associative operator, see Ocaml_operators
for more information.
Floating-point multiplication. Left-associative operator, see Ocaml_operators
for more information.
Floating-point division. Left-associative operator, see Ocaml_operators
for more information.
Exponentiation. Right-associative operator, see Ocaml_operators
for more information.
expm1 x
computes exp x -. 1.0
, giving numerically-accurate results even if x
is close to 0.0
.
Arc cosine. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and is between 0.0
and pi
.
Arc sine. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and is between -pi/2
and pi/2
.
atan2 y x
returns the arc tangent of y /. x
. The signs of x
and y
are used to determine the quadrant of the result. Result is in radians and is between -pi
and pi
.
hypot x y
returns sqrt(x *. x + y *. y)
, that is, the length of the hypotenuse of a right-angled triangle with sides of length x
and y
, or, equivalently, the distance of the point (x,y)
to origin. If one of x
or y
is infinite, returns infinity
even if the other is nan
.
Hyperbolic arc cosine. The argument must fall within the range [1.0, inf]
. Result is in radians and is between 0.0
and inf
.
log1p x
computes log(1.0 +. x)
(natural logarithm), giving numerically-accurate results even if x
is close to 0.0
.
Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians.
Hyperbolic arc tangent. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and ranges over the entire real line.
Round above to an integer value. ceil f
returns the least integer value greater than or equal to f
. The result is returned as a float.
Round below to an integer value. floor f
returns the greatest integer value less than or equal to f
. The result is returned as a float.
copysign x y
returns a float whose absolute value is that of x
and whose sign is that of y
. If x
is nan
, returns nan
. If y
is nan
, returns either x
or -. x
, but it is not specified which.
mod_float a b
returns the remainder of a
with respect to b
. The returned value is a -. n *. b
, where n
is the quotient a /. b
rounded towards zero to an integer.
frexp f
returns the pair of the significant and the exponent of f
. When f
is zero, the significant x
and the exponent n
of f
are equal to zero. When f
is non-zero, they are defined by f = x *. 2 ** n
and 0.5 <= x < 1.0
.
Truncate the given floating-point number to an integer. The result is unspecified if the argument is nan
or falls outside the range of representable integers.
A special floating-point value denoting the result of an undefined operation such as 0.0 /. 0.0
. Stands for 'not a number'. Any floating-point operation with nan
as argument returns nan
as result, unless otherwise specified in IEEE 754 standard. As for floating-point comparisons, =
, <
, <=
, >
and >=
return false
and <>
returns true
if one or both of their arguments is nan
.
nan
is a quiet NaN since 5.1; it was a signaling NaN before.
The difference between 1.0
and the smallest exactly representable floating-point number greater than 1.0
.
The five classes of floating-point numbers, as determined by the Stdlib.classify_float
function.
val classify_float : float -> fpclass
Return the class of the given floating-point number: normal, subnormal, zero, infinite, or not a number.
More in Stdlib.String
More in Stdlib.Char
include sig ... end
include sig ... end
Return the string representation of a boolean. As the returned values may be shared, the user should not modify them directly.
Convert the given string to a boolean.
Return None
if the string is not "true"
or "false"
.
Same as Stdlib.bool_of_string_opt
, but raise Invalid_argument "bool_of_string"
instead of returning None
.
Convert the given string to an integer. The string is read in decimal (by default, or if the string begins with 0u
), in hexadecimal (if it begins with 0x
or 0X
), in octal (if it begins with 0o
or 0O
), or in binary (if it begins with 0b
or 0B
).
The 0u
prefix reads the input as an unsigned integer in the range [0, 2*max_int+1]
. If the input exceeds max_int
it is converted to the signed integer min_int + input - max_int - 1
.
The _
(underscore) character can appear anywhere in the string and is ignored.
Return None
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 int
.
Same as Stdlib.int_of_string_opt
, but raise Failure "int_of_string"
instead of returning None
.
Return a string representation of a floating-point number.
This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see Printf
.
Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by 0x
or 0X
).
The format of decimal floating-point numbers is [-] dd.ddd (e|E) [+|-] dd
, where d
stands for a decimal digit.
The format of hexadecimal floating-point numbers is [-] 0(x|X) hh.hhh (p|P) [+|-] dd
, where h
stands for an hexadecimal digit and d
for a decimal digit.
In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional.
The _
(underscore) character can appear anywhere in the string and is ignored.
Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon.
Return None
if the given string is not a valid representation of a float.
More in Stdlib.List
include sig ... end
l0 @ l1
appends l1
to l0
. Same function as List.append
. Right-associative operator, see Ocaml_operators
for more information.
This is regular, unmocked, IO.
include sig ... end
val stdin : in_channel
The standard input for the process.
val stdout : out_channel
The standard output for the process.
val stderr : out_channel
The standard error output for the process.
Print a floating-point number, in decimal, on standard output.
The conversion of the number to a string uses string_of_float
and can involve a loss of precision.
Print a string, followed by a newline character, on standard output and flush standard output.
Print a newline character on standard output, and flush standard output. This can be used to simulate line buffering of standard output.
Print a floating-point number, in decimal, on standard error.
The conversion of the number to a string uses string_of_float
and can involve a loss of precision.
Print a string, followed by a newline character on standard error and flush standard error.
Print a newline character on standard error, and flush standard error.
Flush standard output, then read characters from standard input until a newline character is encountered.
Return the string of all characters read, without the newline character at the end.
Flush standard output, then read one line from standard input and convert it to an integer.
Return None
if the line read is not a valid representation of an integer.
Same as Stdlib.read_int_opt
, but raise Failure "int_of_string"
instead of returning None
.
Flush standard output, then read one line from standard input and convert it to a floating-point number.
Return None
if the line read is not a valid representation of a floating-point number.
Same as Stdlib.read_float_opt
, but raise Failure "float_of_string"
instead of returning None
.
type open_flag =
| Open_rdonly
open for reading.
*)| Open_wronly
open for writing.
*)| Open_append
open for appending: always write at end of file.
*)| Open_creat
create the file if it does not exist.
*)| Open_trunc
empty the file if it already exists.
*)| Open_excl
fail if Open_creat and the file already exists.
*)| Open_binary
open in binary mode (no conversion).
*)| Open_text
open in text mode (may perform conversions).
*)| Open_nonblock
open in non-blocking mode.
*)Opening modes for Stdlib.open_out_gen
and Stdlib.open_in_gen
.
val open_out : string -> out_channel
Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists.
val open_out_bin : string -> out_channel
Same as Stdlib.open_out
, but the file is opened in binary mode, so that no translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like Stdlib.open_out
.
val open_out_gen : open_flag list -> int -> string -> out_channel
open_out_gen mode perm filename
opens the named file for writing, as described above. The extra argument mode
specifies the opening mode. The extra argument perm
specifies the file permissions, in case the file must be created. Stdlib.open_out
and Stdlib.open_out_bin
are special cases of this function.
val flush : out_channel -> unit
Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time.
val output_char : out_channel -> char -> unit
Write the character on the given output channel.
val output_string : out_channel -> string -> unit
Write the string on the given output channel.
val output_bytes : out_channel -> bytes -> unit
Write the byte sequence on the given output channel.
val output : out_channel -> bytes -> int -> int -> unit
output oc buf pos len
writes len
characters from byte sequence buf
, starting at offset pos
, to the given output channel oc
.
val output_substring : out_channel -> string -> int -> int -> unit
Same as output
but take a string as argument instead of a byte sequence.
val output_byte : out_channel -> int -> unit
Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256.
val output_binary_int : out_channel -> int -> unit
Write one integer in binary format (4 bytes, big-endian) on the given output channel. The given integer is taken modulo 232. The only reliable way to read it back is through the Stdlib.input_binary_int
function. The format is compatible across all machines for a given version of OCaml.
val output_value : out_channel -> 'a -> unit
Write the representation of a structured value of any type to a channel. Circularities and sharing inside the value are detected and preserved. The object can be read back, by the function Stdlib.input_value
. See the description of module Marshal
for more information. Stdlib.output_value
is equivalent to Marshal.to_channel
with an empty list of flags.
val seek_out : out_channel -> int -> unit
seek_out chan pos
sets the current writing position to pos
for channel chan
. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified.
val pos_out : out_channel -> int
Return the current writing position for the given channel. Does not work on channels opened with the Open_append
flag (returns unspecified results). For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with pos_out
, then going back to this position using seek_out
will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode.
val out_channel_length : out_channel -> int
Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless.
val close_out : out_channel -> unit
Close the given channel, flushing all buffered write operations. Output functions raise a Sys_error
exception when they are applied to a closed output channel, except close_out
and flush
, which do nothing when applied to an already closed channel. Note that close_out
may raise Sys_error
if the operating system signals an error when flushing or closing.
val close_out_noerr : out_channel -> unit
Same as close_out
, but ignore all errors.
val set_binary_mode_out : out_channel -> bool -> unit
set_binary_mode_out oc true
sets the channel oc
to binary mode: no translations take place during output. set_binary_mode_out oc false
sets the channel oc
to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from \n
to \r\n
. This function has no effect under operating systems that do not distinguish between text mode and binary mode.
val open_in : string -> in_channel
Open the named file for reading, and return a new input channel on that file, positioned at the beginning of the file.
val open_in_bin : string -> in_channel
Same as Stdlib.open_in
, but the file is opened in binary mode, so that no translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like Stdlib.open_in
.
val open_in_gen : open_flag list -> int -> string -> in_channel
open_in_gen mode perm filename
opens the named file for reading, as described above. The extra arguments mode
and perm
specify the opening mode and file permissions. Stdlib.open_in
and Stdlib.open_in_bin
are special cases of this function.
val input_char : in_channel -> char
Read one character from the given input channel.
val input_line : in_channel -> string
Read characters from the given input channel, until a newline character is encountered. Return the string of all characters read, without the newline character at the end.
val input : in_channel -> bytes -> int -> int -> int
input ic buf pos len
reads up to len
characters from the given channel ic
, storing them in byte sequence buf
, starting at character number pos
. It returns the actual number of characters read, between 0 and len
(inclusive). A return value of 0 means that the end of file was reached. A return value between 0 and len
exclusive means that not all requested len
characters were read, either because no more characters were available at that time, or because the implementation found it convenient to do a partial read; input
must be called again to read the remaining characters, if desired. (See also Stdlib.really_input
for reading exactly len
characters.) Exception Invalid_argument "input"
is raised if pos
and len
do not designate a valid range of buf
.
val really_input : in_channel -> bytes -> int -> int -> unit
really_input ic buf pos len
reads len
characters from channel ic
, storing them in byte sequence buf
, starting at character number pos
.
val really_input_string : in_channel -> int -> string
really_input_string ic len
reads len
characters from channel ic
and returns them in a new string.
val input_byte : in_channel -> int
Same as Stdlib.input_char
, but return the 8-bit integer representing the character.
val input_binary_int : in_channel -> int
Read an integer encoded in binary format (4 bytes, big-endian) from the given input channel. See Stdlib.output_binary_int
.
val input_value : in_channel -> 'a
Read the representation of a structured value, as produced by Stdlib.output_value
, and return the corresponding value. This function is identical to Marshal.from_channel
; see the description of module Marshal
for more information, in particular concerning the lack of type safety.
val seek_in : in_channel -> int -> unit
seek_in chan pos
sets the current reading position to pos
for channel chan
. This works only for regular files. On files of other kinds, the behavior is unspecified.
val pos_in : in_channel -> int
Return the current reading position for the given channel. For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with pos_in
, then going back to this position using seek_in
will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode.
val in_channel_length : in_channel -> int
Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode.
val close_in : in_channel -> unit
Close the given channel. Input functions raise a Sys_error
exception when they are applied to a closed input channel, except close_in
, which does nothing when applied to an already closed channel.
val close_in_noerr : in_channel -> unit
Same as close_in
, but ignore all errors.
val set_binary_mode_in : in_channel -> bool -> unit
set_binary_mode_in ic true
sets the channel ic
to binary mode: no translations take place during input. set_binary_mode_out ic false
sets the channel ic
to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from \r\n
to \n
. This function has no effect under operating systems that do not distinguish between text mode and binary mode.
module LargeFile : sig ... end
Operations on large files. This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type int64
) instead of regular integers (type int
), these alternate functions allow operating on files whose sizes are greater than max_int
.
include sig ... end
The type of references (mutable indirection cells) containing a value of type 'a
.
val ref : 'a -> 'a ref
Return a fresh reference containing the given value.
val (!) : 'a ref -> 'a
!r
returns the current contents of reference r
. Equivalent to fun r -> r.contents
. Unary operator, see Ocaml_operators
for more information.
val (:=) : 'a ref -> 'a -> unit
r := a
stores the value of a
in reference r
. Equivalent to fun r v -> r.contents <- v
. Right-associative operator, see Ocaml_operators
for more information.
val incr : int ref -> unit
Increment the integer contained in the given reference. Equivalent to fun r -> r := succ !r
.
val decr : int ref -> unit
Decrement the integer contained in the given reference. Equivalent to fun r -> r := pred !r
.
More in Stdlib.Result
More in Stdlib.Scanf
, Stdlib.Printf
, and Stdlib.Format
include sig ... end
type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6
type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4
format_of_string s
returns a format string read from the string literal s
. Note: format_of_string
can not convert a string argument that is not a literal. If you need this functionality, use the more general Scanf.format_from_string
function.
val (^^) :
+ ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
+ ('f, 'b, 'c, 'e, 'g, 'h) format6 ->
+ ('a, 'b, 'c, 'd, 'g, 'h) format6
f1 ^^ f2
catenates format strings f1
and f2
. The result is a format string that behaves as the concatenation of format strings f1
and f2
: in case of formatted output, it accepts arguments from f1
, then arguments from f2
; in case of formatted input, it returns results from f1
, then results from f2
. Right-associative operator, see Ocaml_operators
for more information.
include sig ... end
Terminate the process, returning the given status code to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. All open output channels are flushed with flush_all
. The callbacks registered with Domain.at_exit
are called followed by those registered with Stdlib.at_exit
.
An implicit exit 0
is performed each time a program terminates normally. An implicit exit 2
is performed if the program terminates early because of an uncaught exception.
Register the given function to be called at program termination time. The functions registered with at_exit
will be called when the program does any of the following:
Stdlib.exit
caml_shutdown
. The functions are called in 'last in, first out' order: the function most recently added with at_exit
is called first.include sig ... end
module Char : Char_alerting
module Digest : Digest_alerting
module Filename : Filename_alerting
module Float : Float_alerting
module Hashtbl : Hashtbl_alerting
module List : List_alerting
module ListLabels : ListLabels_alerting
module MoreLabels : MoreLabels_alerting
module Printexc : Printexc_alerting
module Printf : Printf_alerting
module Scanf : Scanf_alerting
module Seq : Seq_alerting
module StdLabels : StdLabels_alerting
module String : String_alerting
module StringLabels : StringLabels_alerting
module Uchar : Uchar_alerting
Modules containing advanced features for interacting with the runtime system.
include sig ... end
Stdlib_alerts
Variants of Stdlib
, but with signature items that can be restricted annotated with alerts.
There is one "variant" of the Stdlib
interface implemented, namely Stdlib_alerting
. Alerts are placed on signature items (types, values, and modules) so that those items can be restricted.
The following alerts are used:
physical_eq
: all kinds of physical comparisonsdebug_macro
: macros like __LOC__
list_op
: operations on listsinput_output
: all kinds of real IOimpure
: references, arrays, and other imperative programming constructsunsafe
: generally unsafe operationsBy default, for a "safe" sandbox environment, the following alerts should be enabled: physical_eq
, input_output
, impure
, unsafe
. The remaining alerts are intended for specific situtations and exercises where more needs to be restricted.
Similar modules for Thread
and Event
are in Threads_alerts
to avoid unnecessary dependencies.
module type Char_alerting = sig ... end
module type Digest_alerting = sig ... end
module type Filename_alerting = sig ... end
module type Float_alerting = sig ... end
module type Hashtbl_alerting = sig ... end
module type List_alerting = sig ... end
module type ListLabels_alerting = sig ... end
module type MoreLabels_alerting = sig ... end
module type Printexc_alerting = sig ... end
module type Printf_alerting = sig ... end
module type Scanf_alerting = sig ... end
module type Seq_alerting = sig ... end
module type StringLabels_alerting = sig ... end
module type StdLabels_alerting = sig ... end
module type String_alerting = sig ... end
module type Uchar_alerting = sig ... end
module type Stdlib_alerting = sig ... end
Derived from Stdlib
, but with items that can be restricted annotated with alerts.
module Stdlib_alerting : Stdlib_alerting
Stdlib
, but with the above module type.
Stdlib_alerts.Char_alerting
include sig ... end
Return a string representing the given character, with special characters escaped following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash, double-quote, and single-quote.
Convert the given character to its equivalent lowercase character, using the US-ASCII character set.
Convert the given character to its equivalent uppercase character, using the US-ASCII character set.
The 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 seeded_hash : int -> t -> int
A seeded hash function for characters, with the same output value as Hashtbl.seeded_hash
. This function allows this module to be passed as argument to the functor Hashtbl.MakeSeeded
.
val hash : t -> int
An unseeded hash function for characters, with the same output value as Hashtbl.hash
. This function allows this module to be passed as argument to the functor Hashtbl.Make
.
Stdlib_alerts.Digest_alerting
include sig ... end
The comparison function for 16-character digest, with the same specification as Stdlib.compare
and the implementation shared with String.compare
. Along with the type t
, this function compare
allows the module Digest
to be passed as argument to the functors Set.Make
and Map.Make
.
val string : string -> t
Return the digest of the given string.
val substring : string -> int -> int -> t
Digest.substring s ofs len
returns the digest of the substring of s
starting at index ofs
and containing len
characters.
val to_hex : t -> string
Return the printable hexadecimal representation of the given digest.
val from_hex : string -> t
Convert a hexadecimal representation back into the corresponding digest.
val bytes : bytes -> t
Return the digest of the given byte sequence.
val subbytes : bytes -> int -> int -> t
Digest.subbytes s ofs len
returns the digest of the subsequence of s
starting at index ofs
and containing len
bytes.
val channel : Stdlib.in_channel -> int -> t
If len
is nonnegative, Digest.channel ic len
reads len
characters from channel ic
and returns their digest, or raises End_of_file
if end-of-file is reached before len
characters are read. If len
is negative, Digest.channel ic len
reads all characters from ic
until end-of-file is reached and return their digest.
val file : string -> t
Return the digest of the file whose name is given.
val output : Stdlib.out_channel -> t -> unit
Write a digest on the given output channel.
val input : Stdlib.in_channel -> t
Read a digest from the given input channel.
Stdlib_alerts.Filename_alerting
include sig ... end
The conventional name for the parent of the current directory (e.g. ..
in Unix).
concat dir file
returns a file name that designates file file
in directory dir
.
Return true
if the file name is relative to the current directory, false
if it is absolute (i.e. in Unix, starts with /
).
Return true
if the file name is relative and does not start with an explicit reference to the current directory (./
or ../
in Unix), false
if it starts with an explicit reference to the root directory or the current directory.
check_suffix name suff
returns true
if the filename name
ends with the suffix suff
.
Under Windows ports (including Cygwin), comparison is case-insensitive, relying on String.lowercase_ascii
. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows.
chop_suffix name suff
removes the suffix suff
from the filename name
.
chop_suffix_opt ~suffix filename
removes the suffix from the filename
if possible, or returns None
if the filename does not end with the suffix.
Under Windows ports (including Cygwin), comparison is case-insensitive, relying on String.lowercase_ascii
. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows.
extension name
is the shortest suffix ext
of name0
where:
name0
is the longest suffix of name
that does not contain a directory separator;ext
starts with a period;ext
is preceded by at least one non-period character in name0
.If such a suffix does not exist, extension name
is the empty string.
Return the given file name without its extension, as defined in Filename.extension
. If the extension is empty, the function returns the given file name.
The following invariant holds for any file name s
:
remove_extension s ^ extension s = s
Same as Filename.remove_extension
, but raise Invalid_argument
if the given name has an empty extension.
Split a file name into directory name / base file name. If name
is a valid file name, then concat (dirname name) (basename name)
returns a file name which is equivalent to name
. Moreover, after setting the current directory to dirname name
(with Sys.chdir
), references to basename name
(which is a relative file name) designate the same file as name
before the call to Sys.chdir
.
This function conforms to the specification of POSIX.1-2008 for the basename
utility.
See Filename.basename
. This function conforms to the specification of POSIX.1-2008 for the dirname
utility.
null
is "/dev/null"
on POSIX and "NUL"
on Windows. It represents a file on the OS that discards all writes and returns end of file on reads.
Return a quoted version of a file name, suitable for use as one argument in a command line, escaping all meta-characters. Warning: under Windows, the output is only suitable for use with programs that follow the standard Windows quoting conventions.
val quote_command :
+ string ->
+ ?stdin:string ->
+ ?stdout:string ->
+ ?stderr:string ->
+ string list ->
+ string
quote_command cmd args
returns a quoted command line, suitable for use as an argument to Sys.command
, Unix.system
, and the Unix.open_process
functions.
The string cmd
is the command to call. The list args
is the list of arguments to pass to this command. It can be empty.
The optional arguments ?stdin
and ?stdout
and ?stderr
are file names used to redirect the standard input, the standard output, or the standard error of the command. If ~stdin:f
is given, a redirection < f
is performed and the standard input of the command reads from file f
. If ~stdout:f
is given, a redirection > f
is performed and the standard output of the command is written to file f
. If ~stderr:f
is given, a redirection 2> f
is performed and the standard error of the command is written to file f
. If both ~stdout:f
and ~stderr:f
are given, with the exact same file name f
, a 2>&1
redirection is performed so that the standard output and the standard error of the command are interleaved and redirected to the same file f
.
Under Unix and Cygwin, the command, the arguments, and the redirections if any are quoted using Filename.quote
, then concatenated. Under Win32, additional quoting is performed as required by the cmd.exe
shell that is called by Sys.command
.
temp_file prefix suffix
returns the name of a fresh temporary file in the temporary directory. The base name of the temporary file is formed by concatenating prefix
, then a suitably chosen integer number, then suffix
. The optional argument temp_dir
indicates the temporary directory to use, defaulting to the current result of Filename.get_temp_dir_name
. The temporary file is created empty, with permissions 0o600
(readable and writable only by the file owner). The file is guaranteed to be different from any other file that existed when temp_file
was called.
val open_temp_file :
+ ?mode:Stdlib.open_flag list ->
+ ?perms:int ->
+ ?temp_dir:string ->
+ string ->
+ string ->
+ string * Stdlib.out_channel
Same as Filename.temp_file
, but returns both the name of a fresh temporary file, and an output channel opened (atomically) on this file. This function is more secure than temp_file
: there is no risk that the temporary file will be modified (e.g. replaced by a symbolic link) before the program opens it. The optional argument mode
is a list of additional flags to control the opening of the file. It can contain one or several of Open_append
, Open_binary
, and Open_text
. The default is [Open_text]
(open in text mode). The file is created with permissions perms
(defaults to readable and writable only by the file owner, 0o600
).
temp_dir prefix suffix
creates and returns the name of a fresh temporary directory with permissions perms
(defaults to 0o700) inside temp_dir
. The base name of the temporary directory is formed by concatenating prefix
, then a suitably chosen integer number, then suffix
. The optional argument temp_dir
indicates the temporary directory to use, defaulting to the current result of Filename.get_temp_dir_name
. The temporary directory is created empty, with permissions 0o700
(readable, writable, and searchable only by the file owner). The directory is guaranteed to be different from any other directory that existed when temp_dir
was called.
If temp_dir does not exist, this function does not create it. Instead, it raises Sys_error.
The name of the temporary directory: Under Unix, the value of the TMPDIR
environment variable, or "/tmp" if the variable is not set. Under Windows, the value of the TEMP
environment variable, or "." if the variable is not set. The temporary directory can be changed with Filename.set_temp_dir_name
.
Float_alerting.Array
Float arrays with packed representation.
val length : t -> int
Return the length (number of elements) of the given floatarray.
val get : t -> int -> float
get a n
returns the element number n
of floatarray a
.
val set : t -> int -> float -> unit
set a n x
modifies floatarray a
in place, replacing element number n
with x
.
val make : int -> float -> t
make n x
returns a fresh floatarray of length n
, initialized with x
.
val create : int -> t
create n
returns a fresh floatarray of length n
, with uninitialized data.
val init : int -> (int -> float) -> t
init n f
returns a fresh floatarray of length n
, with element number i
initialized to the result of f i
. In other terms, init n f
tabulates the results of f
applied to the integers 0
to n-1
.
append v1 v2
returns a fresh floatarray containing the concatenation of the floatarrays v1
and v2
.
sub a pos len
returns a fresh floatarray of length len
, containing the elements number pos
to pos + len - 1
of floatarray a
.
copy a
returns a copy of a
, that is, a fresh floatarray containing the same elements as a
.
val fill : t -> int -> int -> float -> unit
fill a pos len x
modifies the floatarray a
in place, storing x
in elements number pos
to pos + len - 1
.
blit src src_pos dst dst_pos len
copies len
elements from floatarray src
, starting at element number src_pos
, to floatarray dst
, starting at element number dst_pos
. It works correctly even if src
and dst
are the same floatarray, and the source and destination chunks overlap.
val to_list : t -> float list
to_list a
returns the list of all the elements of a
.
val of_list : float list -> t
of_list l
returns a fresh floatarray containing the elements of l
.
val iter : (float -> unit) -> t -> unit
iter f a
applies function f
in turn to all the elements of a
. It is equivalent to f a.(0); f a.(1); ...; f a.(length a - 1); ()
.
val iteri : (int -> float -> unit) -> t -> unit
Same as iter
, but the function is applied with the index of the element as first argument, and the element itself as second argument.
map f a
applies function f
to all the elements of a
, and builds a floatarray with the results returned by f
.
val map_inplace : (float -> float) -> t -> unit
map_inplace f a
applies function f
to all elements of a
, and updates their values in place.
Same as map
, but the function is applied to the index of the element as first argument, and the element itself as second argument.
val mapi_inplace : (int -> float -> float) -> t -> unit
Same as map_inplace
, but the function is applied to the index of the element as first argument, and the element itself as second argument.
val fold_left : ('acc -> float -> 'acc) -> 'acc -> t -> 'acc
fold_left f x init
computes f (... (f (f x init.(0)) init.(1)) ...) init.(n-1)
, where n
is the length of the floatarray init
.
val fold_right : (float -> 'acc -> 'acc) -> t -> 'acc -> 'acc
fold_right f a init
computes f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))
, where n
is the length of the floatarray a
.
Array.iter2 f a b
applies function f
to all the elements of a
and b
.
map2 f a b
applies function f
to all the elements of a
and b
, and builds a floatarray with the results returned by f
: [| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]
.
val for_all : (float -> bool) -> t -> bool
for_all f [|a1; ...; an|]
checks if all elements of the floatarray satisfy the predicate f
. That is, it returns (f a1) && (f a2) && ... && (f an)
.
val exists : (float -> bool) -> t -> bool
exists f [|a1; ...; an|]
checks if at least one element of the floatarray satisfies the predicate f
. That is, it returns (f a1) || (f a2) || ... || (f an)
.
val mem : float -> t -> bool
mem a set
is true if and only if there is an element of set
that is structurally equal to a
, i.e. there is an x
in set
such that compare a x = 0
.
val mem_ieee : float -> t -> bool
Same as mem
, but uses IEEE equality instead of structural equality.
val find_opt : (float -> bool) -> t -> float option
val find_index : (float -> bool) -> t -> int option
find_index f a
returns Some i
, where i
is the index of the first element of the array a
that satisfies f x
, if there is such an element.
It returns None
if there is no such element.
val find_map : (float -> 'a option) -> t -> 'a option
val find_mapi : (int -> float -> 'a option) -> t -> 'a option
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
val sort : (float -> float -> int) -> t -> unit
Sort a floatarray in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, Stdlib.compare
is a suitable comparison function. After calling sort
, the array is sorted in place in increasing order. sort
is guaranteed to run in constant heap space and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant stack space.
Specification of the comparison function: Let a
be the floatarray and cmp
the comparison function. The following must be true for all x
, y
, z
in a
:
cmp x y
> 0 if and only if cmp y x
< 0cmp x y
>= 0 and cmp y z
>= 0 then cmp x z
>= 0When sort
returns, a
contains the same elements as before, reordered in such a way that for all i and j valid indices of a
:
cmp a.(i) a.(j)
>= 0 if and only if i >= jval stable_sort : (float -> float -> int) -> t -> unit
Same as sort
, but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space.
The current implementation uses Merge Sort. It uses a temporary floatarray of length n/2
, where n
is the length of the floatarray. It is usually faster than the current implementation of sort
.
val fast_sort : (float -> float -> int) -> t -> unit
Same as sort
or stable_sort
, whichever is faster on typical input.
val to_seq : t -> float Stdlib.Seq.t
Iterate on the floatarray, in increasing order. Modifications of the floatarray during iteration will be reflected in the sequence.
val to_seqi : t -> (int * float) Stdlib.Seq.t
Iterate on the floatarray, in increasing order, yielding indices along elements. Modifications of the floatarray during iteration will be reflected in the sequence.
val of_seq : float Stdlib.Seq.t -> t
Create an array from the generator.
val map_to_array : (float -> 'a) -> t -> 'a array
map_to_array f a
applies function f
to all the elements of a
, and builds an array with the results returned by f
: [| f a.(0); f a.(1); ...; f a.(length a - 1) |]
.
val map_from_array : ('a -> float) -> 'a array -> t
map_from_array f a
applies function f
to all the elements of a
, and builds a floatarray with the results returned by f
.
Care must be taken when concurrently accessing float arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results.
Every float array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays.
For example, consider the following program:
let size = 100_000_000
+let a = Float.Array.make size 1.
+let update a f () =
+ Float.Array.iteri (fun i x -> Float.Array.set a i (f x)) a
+let d1 = Domain.spawn (update a (fun x -> x +. 1.))
+let d2 = Domain.spawn (update a (fun x -> 2. *. x +. 1.))
+let () = Domain.join d1; Domain.join d2
After executing this code, each field of the float array a
is either 2.
, 3.
, 4.
or 5.
. If atomicity is required, then the user must implement their own synchronization (for example, using Mutex.t
).
If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains.
A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains.
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements.
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location with a few exceptions.
Float arrays have two supplementary caveats in the presence of data races.
First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution.
For instance, at the end of
let zeros = Float.Array.make size 0.
+let max_floats = Float.Array.make size Float.max_float
+let res = Float.Array.copy zeros
+let d1 = Domain.spawn (fun () -> Float.Array.blit zeros 0 res 0 size)
+let d2 = Domain.spawn (fun () -> Float.Array.blit max_floats 0 res 0 size)
+let () = Domain.join d1; Domain.join d2
the res
float array might contain values that are neither 0.
nor max_float
.
Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation.
Float_alerting.ArrayLabels
Float arrays with packed representation (labeled functions).
val length : t -> int
Return the length (number of elements) of the given floatarray.
val get : t -> int -> float
get a n
returns the element number n
of floatarray a
.
val set : t -> int -> float -> unit
set a n x
modifies floatarray a
in place, replacing element number n
with x
.
val make : int -> float -> t
make n x
returns a fresh floatarray of length n
, initialized with x
.
val create : int -> t
create n
returns a fresh floatarray of length n
, with uninitialized data.
val init : int -> f:(int -> float) -> t
init n ~f
returns a fresh floatarray of length n
, with element number i
initialized to the result of f i
. In other terms, init n ~f
tabulates the results of f
applied to the integers 0
to n-1
.
append v1 v2
returns a fresh floatarray containing the concatenation of the floatarrays v1
and v2
.
sub a ~pos ~len
returns a fresh floatarray of length len
, containing the elements number pos
to pos + len - 1
of floatarray a
.
copy a
returns a copy of a
, that is, a fresh floatarray containing the same elements as a
.
val fill : t -> pos:int -> len:int -> float -> unit
fill a ~pos ~len x
modifies the floatarray a
in place, storing x
in elements number pos
to pos + len - 1
.
blit ~src ~src_pos ~dst ~dst_pos ~len
copies len
elements from floatarray src
, starting at element number src_pos
, to floatarray dst
, starting at element number dst_pos
. It works correctly even if src
and dst
are the same floatarray, and the source and destination chunks overlap.
val to_list : t -> float list
to_list a
returns the list of all the elements of a
.
val of_list : float list -> t
of_list l
returns a fresh floatarray containing the elements of l
.
val iter : f:(float -> unit) -> t -> unit
iter ~f a
applies function f
in turn to all the elements of a
. It is equivalent to f a.(0); f a.(1); ...; f a.(length a - 1); ()
.
val iteri : f:(int -> float -> unit) -> t -> unit
Same as iter
, but the function is applied with the index of the element as first argument, and the element itself as second argument.
map ~f a
applies function f
to all the elements of a
, and builds a floatarray with the results returned by f
.
val map_inplace : f:(float -> float) -> t -> unit
map_inplace f a
applies function f
to all elements of a
, and updates their values in place.
Same as map
, but the function is applied to the index of the element as first argument, and the element itself as second argument.
val mapi_inplace : f:(int -> float -> float) -> t -> unit
Same as map_inplace
, but the function is applied to the index of the element as first argument, and the element itself as second argument.
val fold_left : f:('acc -> float -> 'acc) -> init:'acc -> t -> 'acc
fold_left ~f x ~init
computes f (... (f (f x init.(0)) init.(1)) ...) init.(n-1)
, where n
is the length of the floatarray init
.
val fold_right : f:(float -> 'acc -> 'acc) -> t -> init:'acc -> 'acc
fold_right f a init
computes f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))
, where n
is the length of the floatarray a
.
Array.iter2 ~f a b
applies function f
to all the elements of a
and b
.
map2 ~f a b
applies function f
to all the elements of a
and b
, and builds a floatarray with the results returned by f
: [| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]
.
val for_all : f:(float -> bool) -> t -> bool
for_all ~f [|a1; ...; an|]
checks if all elements of the floatarray satisfy the predicate f
. That is, it returns (f a1) && (f a2) && ... && (f an)
.
val exists : f:(float -> bool) -> t -> bool
exists f [|a1; ...; an|]
checks if at least one element of the floatarray satisfies the predicate f
. That is, it returns (f a1) || (f a2) || ... || (f an)
.
val mem : float -> set:t -> bool
mem a ~set
is true if and only if there is an element of set
that is structurally equal to a
, i.e. there is an x
in set
such that compare a x = 0
.
val mem_ieee : float -> set:t -> bool
Same as mem
, but uses IEEE equality instead of structural equality.
val find_opt : f:(float -> bool) -> t -> float option
val find_index : f:(float -> bool) -> t -> int option
find_index ~f a
returns Some i
, where i
is the index of the first element of the array a
that satisfies f x
, if there is such an element.
It returns None
if there is no such element.
val find_map : f:(float -> 'a option) -> t -> 'a option
val find_mapi : f:(int -> float -> 'a option) -> t -> 'a option
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
val sort : cmp:(float -> float -> int) -> t -> unit
Sort a floatarray in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, Stdlib.compare
is a suitable comparison function. After calling sort
, the array is sorted in place in increasing order. sort
is guaranteed to run in constant heap space and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant stack space.
Specification of the comparison function: Let a
be the floatarray and cmp
the comparison function. The following must be true for all x
, y
, z
in a
:
cmp x y
> 0 if and only if cmp y x
< 0cmp x y
>= 0 and cmp y z
>= 0 then cmp x z
>= 0When sort
returns, a
contains the same elements as before, reordered in such a way that for all i and j valid indices of a
:
cmp a.(i) a.(j)
>= 0 if and only if i >= jval stable_sort : cmp:(float -> float -> int) -> t -> unit
Same as sort
, but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space.
The current implementation uses Merge Sort. It uses a temporary floatarray of length n/2
, where n
is the length of the floatarray. It is usually faster than the current implementation of sort
.
val fast_sort : cmp:(float -> float -> int) -> t -> unit
Same as sort
or stable_sort
, whichever is faster on typical input.
val to_seq : t -> float Stdlib.Seq.t
Iterate on the floatarray, in increasing order. Modifications of the floatarray during iteration will be reflected in the sequence.
val to_seqi : t -> (int * float) Stdlib.Seq.t
Iterate on the floatarray, in increasing order, yielding indices along elements. Modifications of the floatarray during iteration will be reflected in the sequence.
val of_seq : float Stdlib.Seq.t -> t
Create an array from the generator.
val map_to_array : f:(float -> 'a) -> t -> 'a array
map_to_array ~f a
applies function f
to all the elements of a
, and builds an array with the results returned by f
: [| f a.(0); f a.(1); ...; f a.(length a - 1) |]
.
val map_from_array : f:('a -> float) -> 'a array -> t
map_from_array ~f a
applies function f
to all the elements of a
, and builds a floatarray with the results returned by f
.
Care must be taken when concurrently accessing float arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results.
Every float array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays.
For example, consider the following program:
let size = 100_000_000
+let a = Float.ArrayLabels.make size 1.
+let update a f () =
+ Float.ArrayLabels.iteri ~f:(fun i x -> Float.Array.set a i (f x)) a
+let d1 = Domain.spawn (update a (fun x -> x +. 1.))
+let d2 = Domain.spawn (update a (fun x -> 2. *. x +. 1.))
+let () = Domain.join d1; Domain.join d2
After executing this code, each field of the float array a
is either 2.
, 3.
, 4.
or 5.
. If atomicity is required, then the user must implement their own synchronization (for example, using Mutex.t
).
If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains.
A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains.
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements.
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location with a few exceptions.
Float arrays have two supplementary caveats in the presence of data races.
First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution.
For instance, at the end of
let zeros = Float.Array.make size 0.
+let max_floats = Float.Array.make size Float.max_float
+let res = Float.Array.copy zeros
+let d1 = Domain.spawn (fun () -> Float.Array.blit zeros 0 res 0 size)
+let d2 = Domain.spawn (fun () -> Float.Array.blit max_floats 0 res 0 size)
+let () = Domain.join d1; Domain.join d2
the res
float array might contain values that are neither 0.
nor max_float
.
Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation.
Stdlib_alerts.Float_alerting
include sig ... end
fma x y z
returns x * y + z
, with a best effort for computing this expression with a single rounding, using either hardware instructions (providing full IEEE compliance) or a software emulation.
On 64-bit Cygwin, 64-bit mingw-w64 and MSVC 2017 and earlier, this function may be emulated owing to known bugs on limitations on these platforms. Note: since software emulation of the fma is costly, make sure that you are using hardware fma support if performance matters.
rem a b
returns the remainder of a
with respect to b
. The returned value is a -. n *. b
, where n
is the quotient a /. b
rounded towards zero to an integer.
succ x
returns the floating point number right after x
i.e., the smallest floating-point number greater than x
. See also next_after
.
pred x
returns the floating-point number right before x
i.e., the greatest floating-point number smaller than x
. See also next_after
.
A special floating-point value denoting the result of an undefined operation such as 0.0 /. 0.0
. Stands for 'not a number'. Any floating-point operation with nan
as argument returns nan
as result, unless otherwise specified in IEEE 754 standard. As for floating-point comparisons, =
, <
, <=
, >
and >=
return false
and <>
returns true
if one or both of their arguments is nan
.
nan
is quiet_nan
since 5.1; it was a signaling NaN before.
Signaling NaN. The corresponding signals do not raise OCaml exception, but the value can be useful for interoperability with C libraries.
The difference between 1.0
and the smallest exactly representable floating-point number greater than 1.0
.
is_finite x
is true
if and only if x
is finite i.e., not infinite and not nan
.
is_infinite x
is true
if and only if x
is infinity
or neg_infinity
.
is_nan x
is true
if and only if x
is not a number (see nan
).
Truncate the given floating-point number to an integer. The result is unspecified if the argument is nan
or falls outside the range of representable integers.
Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by 0x
or 0X
). The format of decimal floating-point numbers is [-] dd.ddd (e|E) [+|-] dd
, where d
stands for a decimal digit. The format of hexadecimal floating-point numbers is [-] 0(x|X) hh.hhh (p|P) [+|-] dd
, where h
stands for an hexadecimal digit and d
for a decimal digit. In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional. The _
(underscore) character can appear anywhere in the string and is ignored. Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon.
Return a string representation of a floating-point number.
This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see Printf
.
This function is an alias for Stdlib.string_of_float
.
The five classes of floating-point numbers, as determined by the classify_float
function.
val classify_float : float -> fpclass
Return the class of the given floating-point number: normal, subnormal, zero, infinite, or not a number.
expm1 x
computes exp x -. 1.0
, giving numerically-accurate results even if x
is close to 0.0
.
log1p x
computes log(1.0 +. x)
(natural logarithm), giving numerically-accurate results even if x
is close to 0.0
.
Arc cosine. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and is between 0.0
and pi
.
Arc sine. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and is between -pi/2
and pi/2
.
atan2 y x
returns the arc tangent of y /. x
. The signs of x
and y
are used to determine the quadrant of the result. Result is in radians and is between -pi
and pi
.
hypot x y
returns sqrt(x *. x +. y *. y)
, that is, the length of the hypotenuse of a right-angled triangle with sides of length x
and y
, or, equivalently, the distance of the point (x,y)
to origin. If one of x
or y
is infinite, returns infinity
even if the other is nan
.
Hyperbolic arc cosine. The argument must fall within the range [1.0, inf]
. Result is in radians and is between 0.0
and inf
.
Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians.
Hyperbolic arc tangent. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and ranges over the entire real line.
Error function. The argument ranges over the entire real line. The result is always within [-1.0, 1.0]
.
Complementary error function (erfc x = 1 - erf x
). The argument ranges over the entire real line. The result is always within [-1.0, 1.0]
.
trunc x
rounds x
to the nearest integer whose absolute value is less than or equal to x
.
round x
rounds x
to the nearest integer with ties (fractional values of 0.5) rounded away from zero, regardless of the current rounding direction. If x
is an integer, +0.
, -0.
, nan
, or infinite, x
itself is returned.
On 64-bit mingw-w64, this function may be emulated owing to a bug in the C runtime library (CRT) on this platform.
Round above to an integer value. ceil f
returns the least integer value greater than or equal to f
. The result is returned as a float.
Round below to an integer value. floor f
returns the greatest integer value less than or equal to f
. The result is returned as a float.
next_after x y
returns the next representable floating-point value following x
in the direction of y
. More precisely, if y
is greater (resp. less) than x
, it returns the smallest (resp. largest) representable number greater (resp. less) than x
. If x
equals y
, the function returns y
. If x
or y
is nan
, a nan
is returned. Note that next_after max_float infinity = infinity
and that next_after 0. infinity
is the smallest denormalized positive number. If x
is the smallest denormalized positive number, next_after x 0. = 0.
copy_sign x y
returns a float whose absolute value is that of x
and whose sign is that of y
. If x
is nan
, returns nan
. If y
is nan
, returns either x
or -. x
, but it is not specified which.
sign_bit x
is true
if and only if the sign bit of x
is set. For example sign_bit 1.
and signbit 0.
are false
while sign_bit (-1.)
and sign_bit (-0.)
are true
.
frexp f
returns the pair of the significant and the exponent of f
. When f
is zero, the significant x
and the exponent n
of f
are equal to zero. When f
is non-zero, they are defined by f = x *. 2 ** n
and 0.5 <= x < 1.0
.
compare x y
returns 0
if x
is equal to y
, a negative integer if x
is less than y
, and a positive integer if x
is greater than y
. compare
treats nan
as equal to itself and less than any other float value. This treatment of nan
ensures that compare
defines a total ordering relation.
min x y
returns the minimum of x
and y
. It returns nan
when x
or y
is nan
. Moreover min (-0.) (+0.) = -0.
max x y
returns the maximum of x
and y
. It returns nan
when x
or y
is nan
. Moreover max (-0.) (+0.) = +0.
min_max x y
is (min x y, max x y)
, just more efficient.
min_num x y
returns the minimum of x
and y
treating nan
as missing values. If both x
and y
are nan
, nan
is returned. Moreover min_num (-0.) (+0.) = -0.
max_num x y
returns the maximum of x
and y
treating nan
as missing values. If both x
and y
are nan
nan
is returned. Moreover max_num (-0.) (+0.) = +0.
min_max_num x y
is (min_num x y, max_num x y)
, just more efficient. Note that in particular min_max_num x nan = (x, x)
and min_max_num nan y = (y, y)
.
val seeded_hash : int -> t -> int
A seeded hash function for floats, with the same output value as Hashtbl.seeded_hash
. This function allows this module to be passed as argument to the functor Hashtbl.MakeSeeded
.
val hash : t -> int
An unseeded hash function for floats, with the same output value as Hashtbl.hash
. This function allows this module to be passed as argument to the functor Hashtbl.Make
.
module Array : sig ... end
Float arrays with packed representation.
module ArrayLabels : sig ... end
Float arrays with packed representation (labeled functions).
Make.H
val hash : t -> int
A hashing function on keys. It must be such that if two keys are equal according to equal
, then they have identical hash values as computed by hash
. Examples: suitable (equal
, hash
) pairs for arbitrary key types include
Hashtbl_alerting.Make
Functor building an implementation of the hashtable structure. The functor Hashtbl.Make
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. Since the hash function is not seeded, the create
operation of the result structure always returns non-randomized hash tables.
module H : HashedType
type key = H.t
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
MakeSeeded.H
val seeded_hash : int -> t -> int
A seeded hashing function on keys. The first argument is the seed. It must be the case that if equal x y
is true, then seeded_hash seed x = seeded_hash seed y
for any value of seed
. A suitable choice for seeded_hash
is the function Hashtbl.seeded_hash
below.
Hashtbl_alerting.MakeSeeded
Functor building an implementation of the hashtable structure. The functor Hashtbl.MakeSeeded
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. The create
operation of the result structure supports the ~random
optional parameter and returns randomized hash tables if ~random:true
is passed or if randomization is globally on (see Hashtbl.randomize
).
module H : SeededHashedType
type key = H.t
val create : ?random:bool -> int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
Stdlib_alerts.Hashtbl_alerting
include sig ... end
Hashtbl.hash x
associates a nonnegative integer to any value of any type. It is guaranteed that if x = y
or Stdlib.compare x y = 0
, then hash x = hash y
. Moreover, hash
always terminates, even on cyclic structures.
A variant of hash
that is further parameterized by an integer seed.
Hashtbl.hash_param meaningful total x
computes a hash value for x
, with the same properties as for hash
. The two extra integer parameters meaningful
and total
give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure x
, stopping after meaningful
meaningful nodes were encountered, or total
nodes (meaningful or not) were encountered. If total
as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of meaningful
and total
means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters meaningful
and total
govern the tradeoff between accuracy and speed. As default choices, hash
and seeded_hash
take meaningful = 10
and total = 100
.
A variant of hash_param
that is further parameterized by an integer seed. Usage: Hashtbl.seeded_hash_param meaningful total seed x
.
val create : ?random:bool -> int -> ('a, 'b) t
Hashtbl.create n
creates a new, empty hash table, with initial size n
. For best results, n
should be on the order of the expected number of elements that will be in the table. The table grows as needed, so n
is just an initial guess.
The optional ~random
parameter (a boolean) controls whether the internal organization of the hash table is randomized at each execution of Hashtbl.create
or deterministic over all executions.
A hash table that is created with ~random
set to false
uses a fixed hash function (hash
) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down.
A hash table that is created with ~random
set to true
uses the seeded hash function seeded_hash
with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among 2^{30}
different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using fold
or iter
is no longer deterministic: elements are enumerated in different orders at different runs of the program.
If no ~random
parameter is given, hash tables are created in non-random mode by default. This default can be changed either programmatically by calling randomize
or by setting the R
flag in the OCAMLRUNPARAM
environment variable.
val clear : ('a, 'b) t -> unit
Empty a hash table. Use reset
instead of clear
to shrink the size of the bucket table to its initial size.
val reset : ('a, 'b) t -> unit
Empty a hash table and shrink the size of the bucket table to its initial size.
val add : ('a, 'b) t -> 'a -> 'b -> unit
Hashtbl.add tbl key data
adds a binding of key
to data
in table tbl
.
Warning: Previous bindings for key
are not removed, but simply hidden. That is, after performing remove
tbl key
, the previous binding for key
, if any, is restored. (Same behavior as with association lists.)
If you desire the classic behavior of replacing elements, see replace
.
val find : ('a, 'b) t -> 'a -> 'b
Hashtbl.find tbl x
returns the current binding of x
in tbl
, or raises Not_found
if no such binding exists.
val find_opt : ('a, 'b) t -> 'a -> 'b option
Hashtbl.find_opt tbl x
returns the current binding of x
in tbl
, or None
if no such binding exists.
val find_all : ('a, 'b) t -> 'a -> 'b list
Hashtbl.find_all tbl x
returns the list of all data associated with x
in tbl
. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table.
val mem : ('a, 'b) t -> 'a -> bool
Hashtbl.mem tbl x
checks if x
is bound in tbl
.
val remove : ('a, 'b) t -> 'a -> unit
Hashtbl.remove tbl x
removes the current binding of x
in tbl
, restoring the previous binding if it exists. It does nothing if x
is not bound in tbl
.
val replace : ('a, 'b) t -> 'a -> 'b -> unit
val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit
Hashtbl.iter f tbl
applies f
to all bindings in table tbl
. f
receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to f
.
The order in which the bindings are passed to f
is unspecified. However, if the table contains several bindings for the same key, they are passed to f
in reverse order of introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.
The behavior is not specified if the hash table is modified by f
during the iteration.
val filter_map_inplace : ('a -> 'b -> 'b option) -> ('a, 'b) t -> unit
Hashtbl.filter_map_inplace f tbl
applies f
to all bindings in table tbl
and update each binding depending on the result of f
. If f
returns None
, the binding is discarded. If it returns Some new_val
, the binding is update to associate the key to new_val
.
Other comments for iter
apply as well.
val fold : ('a -> 'b -> 'acc -> 'acc) -> ('a, 'b) t -> 'acc -> 'acc
Hashtbl.fold f tbl init
computes (f kN dN ... (f k1 d1 init)...)
, where k1 ... kN
are the keys of all bindings in tbl
, and d1 ... dN
are the associated values. Each binding is presented exactly once to f
.
The order in which the bindings are passed to f
is unspecified. However, if the table contains several bindings for the same key, they are passed to f
in reverse order of introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.
The behavior is not specified if the hash table is modified by f
during the iteration.
val length : ('a, 'b) t -> int
Hashtbl.length tbl
returns the number of bindings in tbl
. It takes constant time. Multiple bindings are counted once each, so Hashtbl.length
gives the number of times Hashtbl.iter
calls its first argument.
After a call to Hashtbl.randomize()
, hash tables are created in randomized mode by default: create
returns randomized hash tables, unless the ~random:false
optional parameter is given. The same effect can be achieved by setting the R
parameter in the OCAMLRUNPARAM
environment variable.
It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in create
call Hashtbl.randomize()
at initialization time before any domains are created.
Note that once Hashtbl.randomize()
was called, there is no way to revert to the non-randomized default behavior of create
. This is intentional. Non-randomized hash tables can still be created using Hashtbl.create ~random:false
.
Return true
if the tables are currently created in randomized mode by default, false
otherwise.
Return a copy of the given hashtable. Unlike copy
, rebuild
h
re-hashes all the (key, value) entries of the original table h
. The returned hash table is randomized if h
was randomized, or the optional random
parameter is true, or if the default is to create randomized hash tables; see create
for more information.
rebuild
can safely be used to import a hash table built by an old version of the Hashtbl
module, then marshaled to persistent storage. After unmarshaling, apply rebuild
to produce a hash table for the current version of the Hashtbl
module.
type statistics = {
num_bindings : int;
num_buckets : int;
Number of buckets in the table.
*)max_bucket_length : int;
Maximal number of bindings per bucket.
*)bucket_histogram : int array;
Histogram of bucket sizes. This array histo
has length max_bucket_length + 1
. The value of histo.(i)
is the number of buckets whose size is i
.
}
val stats : ('a, 'b) t -> statistics
Hashtbl.stats tbl
returns statistics about the table tbl
: number of buckets, size of the biggest bucket, distribution of buckets by size.
val to_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t
Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first.
The behavior is not specified if the hash table is modified during the iteration.
val to_seq_keys : ('a, _) t -> 'a Stdlib.Seq.t
Same as Seq.map fst (to_seq m)
val to_seq_values : (_, 'b) t -> 'b Stdlib.Seq.t
Same as Seq.map snd (to_seq m)
val add_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t -> unit
Add the given bindings to the table, using add
val replace_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t -> unit
Add the given bindings to the table, using replace
val of_seq : ('a * 'b) Stdlib.Seq.t -> ('a, 'b) t
Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using replace_seq
, which means that if two pairs have the same key, only the latest one will appear in the table.
module type HashedType = sig ... end
The input signature of the functor Make
.
Functor building an implementation of the hashtable structure. The functor Hashtbl.Make
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. Since the hash function is not seeded, the create
operation of the result structure always returns non-randomized hash tables.
module type SeededHashedType = sig ... end
The input signature of the functor MakeSeeded
.
module type SeededS = sig ... end
The output signature of the functor MakeSeeded
.
module MakeSeeded (H : SeededHashedType) : SeededS with type key = H.t
Functor building an implementation of the hashtable structure. The functor Hashtbl.MakeSeeded
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. The create
operation of the result structure supports the ~random
optional parameter and returns randomized hash tables if ~random:true
is passed or if randomization is globally on (see Hashtbl.randomize
).
Hashtbl_alerting.HashedType
The input signature of the functor Make
.
val hash : t -> int
A hashing function on keys. It must be such that if two keys are equal according to equal
, then they have identical hash values as computed by hash
. Examples: suitable (equal
, hash
) pairs for arbitrary key types include
Hashtbl_alerting.S
The output signature of the functor Make
.
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
Hashtbl_alerting.SeededHashedType
The input signature of the functor MakeSeeded
.
val seeded_hash : int -> t -> int
A seeded hashing function on keys. The first argument is the seed. It must be the case that if equal x y
is true, then seeded_hash seed x = seeded_hash seed y
for any value of seed
. A suitable choice for seeded_hash
is the function Hashtbl.seeded_hash
below.
Hashtbl_alerting.SeededS
The output signature of the functor MakeSeeded
.
val create : ?random:bool -> int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
Stdlib_alerts.ListLabels_alerting
include sig ... end
Compare the lengths of two lists. compare_lengths l1 l2
is equivalent to compare (length l1) (length l2)
, except that the computation stops after reaching the end of the shortest list.
Compare the length of a list to an integer. compare_length_with l len
is equivalent to compare (length l) len
, except that the computation stops after at most len
iterations on the list.
is_empty l
is true if and only if l
has no elements. It is equivalent to compare_length_with l 0 = 0
.
Return the n
-th element of the given list. The first element (head of the list) is at position 0.
Return the n
-th element of the given list. The first element (head of the list) is at position 0. Return None
if the list is too short.
init ~len ~f
is [f 0; f 1; ...; f (len-1)]
, evaluated left to right.
append l0 l1
appends l1
to l0
. Same function as the infix operator @
.
rev_append l1 l2
reverses l1
and concatenates it with l2
. This is equivalent to (
rev
l1) @ l2
.
Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument + length of the longest sub-list).
Same as concat
. Not tail-recursive (length of the argument + length of the longest sub-list).
equal eq [a1; ...; an] [b1; ..; bm]
holds when the two input lists have the same length, and for each pair of elements ai
, bi
at the same position we have eq ai bi
.
Note: the eq
function may be called even if the lists have different length. If you know your equality function is costly, you may want to check compare_lengths
first.
compare cmp [a1; ...; an] [b1; ...; bm]
performs a lexicographic comparison of the two input lists, using the same 'a -> 'a -> int
interface as Stdlib.compare
:
a1 :: l1
is smaller than a2 :: l2
(negative result) if a1
is smaller than a2
, or if they are equal (0 result) and l1
is smaller than l2
[]
is strictly smaller than non-empty listsNote: the cmp
function will be called even if the lists have different lengths.
iter ~f [a1; ...; an]
applies function f
in turn to [a1; ...; an]
. It is equivalent to f a1; f a2; ...; f an
.
Same as iter
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
map ~f [a1; ...; an]
applies function f
to a1, ..., an
, and builds the list [f a1; ...; f an]
with the results returned by f
.
Same as map
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
filter_map ~f l
applies f
to every element of l
, filters out the None
elements and returns the list of the arguments of the Some
elements.
fold_left_map
is a combination of fold_left
and map
that threads an accumulator through calls to f
.
fold_left ~f ~init [b1; ...; bn]
is f (... (f (f init b1) b2) ...) bn
.
fold_right ~f [a1; ...; an] ~init
is f a1 (f a2 (... (f an init) ...))
. Not tail-recursive.
iter2 ~f [a1; ...; an] [b1; ...; bn]
calls in turn f a1 b1; ...; f an bn
.
map2 ~f [a1; ...; an] [b1; ...; bn]
is [f a1 b1; ...; f an bn]
.
fold_left2 ~f ~init [a1; ...; an] [b1; ...; bn]
is f (... (f (f init a1 b1) a2 b2) ...) an bn
.
fold_right2 ~f [a1; ...; an] [b1; ...; bn] ~init
is f a1 b1 (f a2 b2 (... (f an bn init) ...))
.
for_all ~f [a1; ...; an]
checks if all elements of the list satisfy the predicate f
. That is, it returns (f a1) && (f a2) && ... && (f an)
for a non-empty list and true
if the list is empty.
exists ~f [a1; ...; an]
checks if at least one element of the list satisfies the predicate f
. That is, it returns (f a1) || (f a2) || ... || (f an)
for a non-empty list and false
if the list is empty.
Same as for_all
, but for a two-argument predicate.
Same as exists
, but for a two-argument predicate.
mem a ~set
is true if and only if a
is equal to an element of set
.
find ~f l
returns the first element of the list l
that satisfies the predicate f
.
find ~f l
returns the first element of the list l
that satisfies the predicate f
. Returns None
if there is no value that satisfies f
in the list l
.
find_index ~f xs
returns Some i
, where i
is the index of the first element of the list xs
that satisfies f x
, if there is such an element.
It returns None
if there is no such element.
find_map ~f l
applies f
to the elements of l
in order, and returns the first result of the form Some v
, or None
if none exist.
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
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 is preserved.
find_all
is another name for filter
.
Same as filter
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
partition ~f l
returns a pair of lists (l1, l2)
, where l1
is the list of all the elements of l
that satisfy the predicate f
, and l2
is the list of all the elements of l
that do not satisfy f
. The order of the elements in the input list is preserved.
partition_map f l
returns a pair of lists (l1, l2)
such that, for each element x
of the input list l
:
f x
is Left y1
, then y1
is in l1
, andf x
is Right y2
, then y2
is in l2
.The output elements are included in l1
and l2
in the same relative order as the corresponding input elements in l
.
In particular, partition_map (fun x -> if f x then Left x else Right x) l
is equivalent to partition f l
.
assoc a l
returns the value associated with key a
in the list of pairs l
. That is, assoc a [ ...; (a,b); ...] = b
if (a,b)
is the leftmost binding of a
in list l
.
assoc_opt a l
returns the value associated with key a
in the list of pairs l
. That is, assoc_opt a [ ...; (a,b); ...] = Some b
if (a,b)
is the leftmost binding of a
in list l
. Returns None
if there is no value associated with a
in the list l
.
Same as assoc
, but simply return true
if a binding exists, and false
if no bindings exist for the given key.
remove_assoc a l
returns the list of pairs l
without the first pair with key a
, if any. Not tail-recursive.
Transform a list of pairs into a pair of lists: split [(a1,b1); ...; (an,bn)]
is ([a1; ...; an], [b1; ...; bn])
. Not tail-recursive.
Transform a pair of lists into a list of pairs: combine [a1; ...; an] [b1; ...; bn]
is [(a1,b1); ...; (an,bn)]
.
Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, Stdlib.compare
is a suitable comparison function. The resulting list is sorted in increasing order. sort
is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space.
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
, but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order).
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
or stable_sort
, whichever is faster on typical input.
Same as sort
, but also remove duplicates.
Merge two lists: Assuming that l1
and l2
are sorted according to the comparison function cmp
, merge ~cmp l1 l2
will return a sorted list containing all the elements of l1
and l2
. If several elements compare equal, the elements of l1
will be before the elements of l2
. Not tail-recursive (sum of the lengths of the arguments).
Same as mem
, but uses physical equality instead of structural equality to compare list elements.
Same as assoc
, but uses physical equality instead of structural equality to compare keys.
Same as assoc_opt
, but uses physical equality instead of structural equality to compare keys.
Same as mem_assoc
, but uses physical equality instead of structural equality to compare keys.
Same as remove_assoc
, but uses physical equality instead of structural equality to compare keys. Not tail-recursive.
Stdlib_alerts.List_alerting
include sig ... end
Compare the lengths of two lists. compare_lengths l1 l2
is equivalent to compare (length l1) (length l2)
, except that the computation stops after reaching the end of the shortest list.
Compare the length of a list to an integer. compare_length_with l len
is equivalent to compare (length l) len
, except that the computation stops after at most len
iterations on the list.
is_empty l
is true if and only if l
has no elements. It is equivalent to compare_length_with l 0 = 0
.
Return the n
-th element of the given list. The first element (head of the list) is at position 0.
Return the n
-th element of the given list. The first element (head of the list) is at position 0. Return None
if the list is too short.
init len f
is [f 0; f 1; ...; f (len-1)]
, evaluated left to right.
append l0 l1
appends l1
to l0
. Same function as the infix operator @
.
rev_append l1 l2
reverses l1
and concatenates it with l2
. This is equivalent to (
rev
l1) @ l2
.
Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument + length of the longest sub-list).
Same as concat
. Not tail-recursive (length of the argument + length of the longest sub-list).
equal eq [a1; ...; an] [b1; ..; bm]
holds when the two input lists have the same length, and for each pair of elements ai
, bi
at the same position we have eq ai bi
.
Note: the eq
function may be called even if the lists have different length. If you know your equality function is costly, you may want to check compare_lengths
first.
compare cmp [a1; ...; an] [b1; ...; bm]
performs a lexicographic comparison of the two input lists, using the same 'a -> 'a -> int
interface as Stdlib.compare
:
a1 :: l1
is smaller than a2 :: l2
(negative result) if a1
is smaller than a2
, or if they are equal (0 result) and l1
is smaller than l2
[]
is strictly smaller than non-empty listsNote: the cmp
function will be called even if the lists have different lengths.
iter f [a1; ...; an]
applies function f
in turn to [a1; ...; an]
. It is equivalent to f a1; f a2; ...; f an
.
Same as iter
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
map f [a1; ...; an]
applies function f
to a1, ..., an
, and builds the list [f a1; ...; f an]
with the results returned by f
.
Same as map
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
filter_map f l
applies f
to every element of l
, filters out the None
elements and returns the list of the arguments of the Some
elements.
fold_left_map
is a combination of fold_left
and map
that threads an accumulator through calls to f
.
fold_left f init [b1; ...; bn]
is f (... (f (f init b1) b2) ...) bn
.
fold_right f [a1; ...; an] init
is f a1 (f a2 (... (f an init) ...))
. Not tail-recursive.
iter2 f [a1; ...; an] [b1; ...; bn]
calls in turn f a1 b1; ...; f an bn
.
map2 f [a1; ...; an] [b1; ...; bn]
is [f a1 b1; ...; f an bn]
.
fold_left2 f init [a1; ...; an] [b1; ...; bn]
is f (... (f (f init a1 b1) a2 b2) ...) an bn
.
fold_right2 f [a1; ...; an] [b1; ...; bn] init
is f a1 b1 (f a2 b2 (... (f an bn init) ...))
.
for_all f [a1; ...; an]
checks if all elements of the list satisfy the predicate f
. That is, it returns (f a1) && (f a2) && ... && (f an)
for a non-empty list and true
if the list is empty.
exists f [a1; ...; an]
checks if at least one element of the list satisfies the predicate f
. That is, it returns (f a1) || (f a2) || ... || (f an)
for a non-empty list and false
if the list is empty.
Same as for_all
, but for a two-argument predicate.
Same as exists
, but for a two-argument predicate.
find f l
returns the first element of the list l
that satisfies the predicate f
.
find f l
returns the first element of the list l
that satisfies the predicate f
. Returns None
if there is no value that satisfies f
in the list l
.
find_index f xs
returns Some i
, where i
is the index of the first element of the list xs
that satisfies f x
, if there is such an element.
It returns None
if there is no such element.
find_map f l
applies f
to the elements of l
in order, and returns the first result of the form Some v
, or None
if none exist.
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
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 is preserved.
find_all
is another name for filter
.
Same as filter
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
partition f l
returns a pair of lists (l1, l2)
, where l1
is the list of all the elements of l
that satisfy the predicate f
, and l2
is the list of all the elements of l
that do not satisfy f
. The order of the elements in the input list is preserved.
partition_map f l
returns a pair of lists (l1, l2)
such that, for each element x
of the input list l
:
f x
is Left y1
, then y1
is in l1
, andf x
is Right y2
, then y2
is in l2
.The output elements are included in l1
and l2
in the same relative order as the corresponding input elements in l
.
In particular, partition_map (fun x -> if f x then Left x else Right x) l
is equivalent to partition f l
.
assoc a l
returns the value associated with key a
in the list of pairs l
. That is, assoc a [ ...; (a,b); ...] = b
if (a,b)
is the leftmost binding of a
in list l
.
assoc_opt a l
returns the value associated with key a
in the list of pairs l
. That is, assoc_opt a [ ...; (a,b); ...] = Some b
if (a,b)
is the leftmost binding of a
in list l
. Returns None
if there is no value associated with a
in the list l
.
Same as assoc
, but simply return true
if a binding exists, and false
if no bindings exist for the given key.
remove_assoc a l
returns the list of pairs l
without the first pair with key a
, if any. Not tail-recursive.
Transform a list of pairs into a pair of lists: split [(a1,b1); ...; (an,bn)]
is ([a1; ...; an], [b1; ...; bn])
. Not tail-recursive.
Transform a pair of lists into a list of pairs: combine [a1; ...; an] [b1; ...; bn]
is [(a1,b1); ...; (an,bn)]
.
Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, Stdlib.compare
is a suitable comparison function. The resulting list is sorted in increasing order. sort
is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space.
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
, but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order).
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
or stable_sort
, whichever is faster on typical input.
Same as sort
, but also remove duplicates.
Merge two lists: Assuming that l1
and l2
are sorted according to the comparison function cmp
, merge cmp l1 l2
will return a sorted list containing all the elements of l1
and l2
. If several elements compare equal, the elements of l1
will be before the elements of l2
. Not tail-recursive (sum of the lengths of the arguments).
Same as mem
, but uses physical equality instead of structural equality to compare list elements.
Same as assoc
, but uses physical equality instead of structural equality to compare keys.
Same as assoc_opt
, but uses physical equality instead of structural equality to compare keys.
Same as mem_assoc
, but uses physical equality instead of structural equality to compare keys.
Same as remove_assoc
, but uses physical equality instead of structural equality to compare keys. Not tail-recursive.
Make.H
val hash : t -> int
A hashing function on keys. It must be such that if two keys are equal according to equal
, then they have identical hash values as computed by hash
. Examples: suitable (equal
, hash
) pairs for arbitrary key types include
Hashtbl.Make
Functor building an implementation of the hashtable structure. The functor Hashtbl.Make
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. Since the hash function is not seeded, the create
operation of the result structure always returns non-randomized hash tables.
module H : HashedType
type key = H.t
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
MakeSeeded.H
val seeded_hash : int -> t -> int
A seeded hashing function on keys. The first argument is the seed. It must be the case that if equal x y
is true, then seeded_hash seed x = seeded_hash seed y
for any value of seed
. A suitable choice for seeded_hash
is the function Hashtbl.seeded_hash
below.
Hashtbl.MakeSeeded
Functor building an implementation of the hashtable structure. The functor Hashtbl.MakeSeeded
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. The create
operation of the result structure supports the ~random
optional parameter and returns randomized hash tables if ~random:true
is passed or if randomization is globally on (see Hashtbl.randomize
).
module H : SeededHashedType
type key = H.t
val create : ?random:bool -> int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
MoreLabels_alerting.Hashtbl
Hash tables and hash functions.
Hash tables are hashed association tables, with in-place modification. Because most operations on a hash table modify their input, they're more commonly used in imperative code. The lookup of the value associated with a key (see find
, find_opt
) is normally very fast, often faster than the equivalent lookup in Map
.
The functors Make
and MakeSeeded
can be used when performance or flexibility are key. The user provides custom equality and hash functions for the key type, and obtains a custom hash table type for this particular type of key.
Warning a hash table is only as good as the hash function. A bad hash function will turn the table into a degenerate association list, with linear time lookup instead of constant time lookup.
The polymorphic t
hash table is useful in simpler cases or in interactive environments. It uses the polymorphic hash
function defined in the OCaml runtime (at the time of writing, it's SipHash), as well as the polymorphic equality (=)
.
See the examples section.
Unsynchronized accesses
Unsynchronized accesses to a hash table may lead to an invalid hash table state. Thus, concurrent accesses to a hash tables must be synchronized (for instance with a Mutex.t
).
val create : ?random:bool -> int -> ('a, 'b) t
Hashtbl.create n
creates a new, empty hash table, with initial size n
. For best results, n
should be on the order of the expected number of elements that will be in the table. The table grows as needed, so n
is just an initial guess.
The optional ~random
parameter (a boolean) controls whether the internal organization of the hash table is randomized at each execution of Hashtbl.create
or deterministic over all executions.
A hash table that is created with ~random
set to false
uses a fixed hash function (hash
) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down.
A hash table that is created with ~random
set to true
uses the seeded hash function seeded_hash
with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among 2^{30}
different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using fold
or iter
is no longer deterministic: elements are enumerated in different orders at different runs of the program.
If no ~random
parameter is given, hash tables are created in non-random mode by default. This default can be changed either programmatically by calling randomize
or by setting the R
flag in the OCAMLRUNPARAM
environment variable.
val clear : ('a, 'b) t -> unit
Empty a hash table. Use reset
instead of clear
to shrink the size of the bucket table to its initial size.
val reset : ('a, 'b) t -> unit
Empty a hash table and shrink the size of the bucket table to its initial size.
val add : ('a, 'b) t -> key:'a -> data:'b -> unit
Hashtbl.add tbl ~key ~data
adds a binding of key
to data
in table tbl
.
Warning: Previous bindings for key
are not removed, but simply hidden. That is, after performing remove
tbl key
, the previous binding for key
, if any, is restored. (Same behavior as with association lists.)
If you desire the classic behavior of replacing elements, see replace
.
val find : ('a, 'b) t -> 'a -> 'b
Hashtbl.find tbl x
returns the current binding of x
in tbl
, or raises Not_found
if no such binding exists.
val find_opt : ('a, 'b) t -> 'a -> 'b option
Hashtbl.find_opt tbl x
returns the current binding of x
in tbl
, or None
if no such binding exists.
val find_all : ('a, 'b) t -> 'a -> 'b list
Hashtbl.find_all tbl x
returns the list of all data associated with x
in tbl
. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table.
val mem : ('a, 'b) t -> 'a -> bool
Hashtbl.mem tbl x
checks if x
is bound in tbl
.
val remove : ('a, 'b) t -> 'a -> unit
Hashtbl.remove tbl x
removes the current binding of x
in tbl
, restoring the previous binding if it exists. It does nothing if x
is not bound in tbl
.
val replace : ('a, 'b) t -> key:'a -> data:'b -> unit
val iter : f:(key:'a -> data:'b -> unit) -> ('a, 'b) t -> unit
Hashtbl.iter ~f tbl
applies f
to all bindings in table tbl
. f
receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to f
.
The order in which the bindings are passed to f
is unspecified. However, if the table contains several bindings for the same key, they are passed to f
in reverse order of introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.
The behavior is not specified if the hash table is modified by f
during the iteration.
val filter_map_inplace :
+ f:(key:'a -> data:'b -> 'b option) ->
+ ('a, 'b) t ->
+ unit
Hashtbl.filter_map_inplace ~f tbl
applies f
to all bindings in table tbl
and update each binding depending on the result of f
. If f
returns None
, the binding is discarded. If it returns Some new_val
, the binding is update to associate the key to new_val
.
Other comments for iter
apply as well.
val fold :
+ f:(key:'a -> data:'b -> 'acc -> 'acc) ->
+ ('a, 'b) t ->
+ init:'acc ->
+ 'acc
Hashtbl.fold ~f tbl ~init
computes (f kN dN ... (f k1 d1 init)...)
, where k1 ... kN
are the keys of all bindings in tbl
, and d1 ... dN
are the associated values. Each binding is presented exactly once to f
.
The order in which the bindings are passed to f
is unspecified. However, if the table contains several bindings for the same key, they are passed to f
in reverse order of introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.
The behavior is not specified if the hash table is modified by f
during the iteration.
val length : ('a, 'b) t -> int
Hashtbl.length tbl
returns the number of bindings in tbl
. It takes constant time. Multiple bindings are counted once each, so Hashtbl.length
gives the number of times Hashtbl.iter
calls its first argument.
After a call to Hashtbl.randomize()
, hash tables are created in randomized mode by default: create
returns randomized hash tables, unless the ~random:false
optional parameter is given. The same effect can be achieved by setting the R
parameter in the OCAMLRUNPARAM
environment variable.
It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in create
call Hashtbl.randomize()
at initialization time before any domains are created.
Note that once Hashtbl.randomize()
was called, there is no way to revert to the non-randomized default behavior of create
. This is intentional. Non-randomized hash tables can still be created using Hashtbl.create ~random:false
.
Return true
if the tables are currently created in randomized mode by default, false
otherwise.
Return a copy of the given hashtable. Unlike copy
, rebuild
h
re-hashes all the (key, value) entries of the original table h
. The returned hash table is randomized if h
was randomized, or the optional random
parameter is true, or if the default is to create randomized hash tables; see create
for more information.
rebuild
can safely be used to import a hash table built by an old version of the Hashtbl
module, then marshaled to persistent storage. After unmarshaling, apply rebuild
to produce a hash table for the current version of the Hashtbl
module.
type statistics = Stdlib.Hashtbl.statistics = {
num_bindings : int;
num_buckets : int;
Number of buckets in the table.
*)max_bucket_length : int;
Maximal number of bindings per bucket.
*)bucket_histogram : int array;
Histogram of bucket sizes. This array histo
has length max_bucket_length + 1
. The value of histo.(i)
is the number of buckets whose size is i
.
}
val stats : ('a, 'b) t -> statistics
Hashtbl.stats tbl
returns statistics about the table tbl
: number of buckets, size of the biggest bucket, distribution of buckets by size.
val to_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t
Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first.
The behavior is not specified if the hash table is modified during the iteration.
val to_seq_keys : ('a, _) t -> 'a Stdlib.Seq.t
Same as Seq.map fst (to_seq m)
val to_seq_values : (_, 'b) t -> 'b Stdlib.Seq.t
Same as Seq.map snd (to_seq m)
val add_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t -> unit
Add the given bindings to the table, using add
val replace_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t -> unit
Add the given bindings to the table, using replace
val of_seq : ('a * 'b) Stdlib.Seq.t -> ('a, 'b) t
Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using replace_seq
, which means that if two pairs have the same key, only the latest one will appear in the table.
The functorial interface allows the use of specific comparison and hash functions, either for performance/security concerns, or because keys are not hashable/comparable with the polymorphic builtins.
For instance, one might want to specialize a table for integer keys:
module IntHash =
+ struct
+ type t = int
+ let equal i j = i=j
+ let hash i = i land max_int
+ end
+
+module IntHashtbl = Hashtbl.Make(IntHash)
+
+let h = IntHashtbl.create 17 in
+IntHashtbl.add h 12 "hello"
This creates a new module IntHashtbl
, with a new type 'a
+ IntHashtbl.t
of tables from int
to 'a
. In this example, h
contains string
values so its type is string IntHashtbl.t
.
Note that the new type 'a IntHashtbl.t
is not compatible with the type ('a,'b) Hashtbl.t
of the generic interface. For example, Hashtbl.length h
would not type-check, you must use IntHashtbl.length
.
module type HashedType = sig ... end
The input signature of the functor Make
.
module Make
+ (H : HashedType) :
+ S with type key = H.t and type 'a t = 'a Stdlib.Hashtbl.Make(H).t
Functor building an implementation of the hashtable structure. The functor Hashtbl.Make
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. Since the hash function is not seeded, the create
operation of the result structure always returns non-randomized hash tables.
module type SeededHashedType = sig ... end
The input signature of the functor MakeSeeded
.
module type SeededS = sig ... end
The output signature of the functor MakeSeeded
.
module MakeSeeded
+ (H : SeededHashedType) :
+ SeededS with type key = H.t and type 'a t = 'a Stdlib.Hashtbl.MakeSeeded(H).t
Functor building an implementation of the hashtable structure. The functor Hashtbl.MakeSeeded
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. The create
operation of the result structure supports the ~random
optional parameter and returns randomized hash tables if ~random:true
is passed or if randomization is globally on (see Hashtbl.randomize
).
Hashtbl.hash x
associates a nonnegative integer to any value of any type. It is guaranteed that if x = y
or Stdlib.compare x y = 0
, then hash x = hash y
. Moreover, hash
always terminates, even on cyclic structures.
A variant of hash
that is further parameterized by an integer seed.
Hashtbl.hash_param meaningful total x
computes a hash value for x
, with the same properties as for hash
. The two extra integer parameters meaningful
and total
give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure x
, stopping after meaningful
meaningful nodes were encountered, or total
nodes (meaningful or not) were encountered. If total
as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of meaningful
and total
means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters meaningful
and total
govern the tradeoff between accuracy and speed. As default choices, hash
and seeded_hash
take meaningful = 10
and total = 100
.
A variant of hash_param
that is further parameterized by an integer seed. Usage: Hashtbl.seeded_hash_param meaningful total seed x
.
(* 0...99 *)
+let seq = Seq.ints 0 |> Seq.take 100
+
+(* build from Seq.t *)
+# let tbl =
+ seq
+ |> Seq.map (fun x -> x, string_of_int x)
+ |> Hashtbl.of_seq
+val tbl : (int, string) Hashtbl.t = <abstr>
+
+# Hashtbl.length tbl
+- : int = 100
+
+# Hashtbl.find_opt tbl 32
+- : string option = Some "32"
+
+# Hashtbl.find_opt tbl 166
+- : string option = None
+
+# Hashtbl.replace tbl 166 "one six six"
+- : unit = ()
+
+# Hashtbl.find_opt tbl 166
+- : string option = Some "one six six"
+
+# Hashtbl.length tbl
+- : int = 101
Given a sequence of elements (here, a Seq.t
), we want to count how many times each distinct element occurs in the sequence. A simple way to do this, assuming the elements are comparable and hashable, is to use a hash table that maps elements to their number of occurrences.
Here we illustrate that principle using a sequence of (ascii) characters (type char
). We use a custom Char_tbl
specialized for char
.
# module Char_tbl = Hashtbl.Make(struct
+ type t = char
+ let equal = Char.equal
+ let hash = Hashtbl.hash
+ end)
+
+(* count distinct occurrences of chars in [seq] *)
+# let count_chars (seq : char Seq.t) : _ list =
+ let counts = Char_tbl.create 16 in
+ Seq.iter
+ (fun c ->
+ let count_c =
+ Char_tbl.find_opt counts c
+ |> Option.value ~default:0
+ in
+ Char_tbl.replace counts c (count_c + 1))
+ seq;
+ (* turn into a list *)
+ Char_tbl.fold (fun c n l -> (c,n) :: l) counts []
+ |> List.sort (fun (c1,_)(c2,_) -> Char.compare c1 c2)
+val count_chars : Char_tbl.key Seq.t -> (Char.t * int) list = <fun>
+
+(* basic seq from a string *)
+# let seq = String.to_seq "hello world, and all the camels in it!"
+val seq : char Seq.t = <fun>
+
+# count_chars seq
+- : (Char.t * int) list =
+[(' ', 7); ('!', 1); (',', 1); ('a', 3); ('c', 1); ('d', 2); ('e', 3);
+ ('h', 2); ('i', 2); ('l', 6); ('m', 1); ('n', 2); ('o', 2); ('r', 1);
+ ('s', 1); ('t', 2); ('w', 1)]
+
+(* "abcabcabc..." *)
+# let seq2 =
+ Seq.cycle (String.to_seq "abc") |> Seq.take 31
+val seq2 : char Seq.t = <fun>
+
+# String.of_seq seq2
+- : String.t = "abcabcabcabcabcabcabcabcabcabca"
+
+# count_chars seq2
+- : (Char.t * int) list = [('a', 11); ('b', 10); ('c', 10)]
Hashtbl.HashedType
The input signature of the functor Make
.
val hash : t -> int
A hashing function on keys. It must be such that if two keys are equal according to equal
, then they have identical hash values as computed by hash
. Examples: suitable (equal
, hash
) pairs for arbitrary key types include
Hashtbl.S
The output signature of the functor Make
.
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
Hashtbl.SeededHashedType
The input signature of the functor MakeSeeded
.
val seeded_hash : int -> t -> int
A seeded hashing function on keys. The first argument is the seed. It must be the case that if equal x y
is true, then seeded_hash seed x = seeded_hash seed y
for any value of seed
. A suitable choice for seeded_hash
is the function Hashtbl.seeded_hash
below.
Hashtbl.SeededS
The output signature of the functor MakeSeeded
.
val create : ?random:bool -> int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
Make.Ord
A total ordering function over the keys. This is a two-argument function f
such that f e1 e2
is zero if the keys e1
and e2
are equal, f e1 e2
is strictly negative if e1
is smaller than e2
, and f e1 e2
is strictly positive if e1
is greater than e2
. Example: a suitable ordering function is the generic structural comparison function Stdlib.compare
.
Map.Make
Functor building an implementation of the map structure given a totally ordered type.
module Ord : OrderedType
type key = Ord.t
The type of the map keys.
val empty : 'a t
The empty map.
add ~key ~data m
returns a map containing the same bindings as m
, plus a binding of key
to data
. If key
was already bound in m
to a value that is physically equal to data
, m
is returned unchanged (the result of the function is then physically equal to m
). Otherwise, the previous binding of key
in m
disappears.
add_to_list ~key ~data m
is m
with key
mapped to l
such that l
is data :: Map.find key m
if key
was bound in m
and [v]
otherwise.
update ~key ~f m
returns a map containing the same bindings as m
, except for the binding of key
. Depending on the value of y
where y
is f (find_opt key m)
, the binding of key
is added, removed or updated. If y
is None
, the binding is removed if it exists; otherwise, if y
is Some z
then key
is associated to z
in the resulting map. If key
was already bound in m
to a value that is physically equal to z
, m
is returned unchanged (the result of the function is then physically equal to m
).
singleton x y
returns the one-element map that contains a binding y
for x
.
remove x m
returns a map containing the same bindings as m
, except for x
which is unbound in the returned map. If x
was not in m
, m
is returned unchanged (the result of the function is then physically equal to m
).
merge ~f m1 m2
computes a map whose keys are a subset of the keys of m1
and of m2
. The presence of each such binding, and the corresponding value, is determined with the function f
. In terms of the find_opt
operation, we have find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)
for any key x
, provided that f x None None = None
.
union ~f m1 m2
computes a map whose keys are a subset of the keys of m1
and of m2
. When the same binding is defined in both arguments, the function f
is used to combine them. This is a special case of merge
: union f m1 m2
is equivalent to merge f' m1 m2
, where
f' _key None None = None
f' _key (Some v) None = Some v
f' _key None (Some v) = Some v
f' key (Some v1) (Some v2) = f key v1 v2
val cardinal : 'a t -> int
Return the number of bindings of a map.
Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering Ord.compare
, where Ord
is the argument given to Map.Make
.
Return the binding with the smallest key in a given map (with respect to the Ord.compare
ordering), or raise Not_found
if the map is empty.
Return the binding with the smallest key in the given map (with respect to the Ord.compare
ordering), or None
if the map is empty.
Same as min_binding
, but returns the binding with the largest key in the given map.
Same as min_binding_opt
, but returns the binding with the largest key in the given map.
Return one binding of the given map, or raise Not_found
if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
Return one binding of the given map, or None
if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
find x m
returns the current value of x
in m
, or raises Not_found
if no binding for x
exists.
find_opt x m
returns Some v
if the current value of x
in m
is v
, or None
if no binding for x
exists.
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.
For example, find_first (fun k -> Ord.compare k x >= 0) m
will return the first binding k, v
of m
where Ord.compare k x >= 0
(intuitively: k >= x
), or raise Not_found
if x
is greater than any element of m
.
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.
find_last ~f m
, where f
is a monotonically decreasing function, returns the binding of m
with the highest key k
such that f k
, or raises Not_found
if no such key exists.
find_last_opt ~f m
, where f
is a monotonically decreasing function, returns an option containing the binding of m
with the highest key k
such that f k
, or None
if no such key exists.
iter ~f m
applies f
to all bindings in map m
. f
receives the key as first argument, and the associated value as second argument. The bindings are passed to f
in increasing order with respect to the ordering over the type of the keys.
fold ~f m ~init
computes (f kN dN ... (f k1 d1 init)...)
, where k1 ... kN
are the keys of all bindings in m
(in increasing order), and d1 ... dN
are the associated data.
map ~f m
returns a map with same domain as m
, where the associated value a
of all bindings of m
has been replaced by the result of the application of f
to a
. The bindings are passed to f
in increasing order with respect to the ordering over the type of the keys.
Same as map
, but the function receives as arguments both the key and the associated value for each binding of the map.
filter ~f m
returns the map with all the bindings in m
that satisfy predicate p
. If every binding in m
satisfies f
, m
is returned unchanged (the result of the function is then physically equal to m
)
filter_map ~f m
applies the function f
to every binding of m
, and builds a map from the results. For each binding (k, v)
in the input map:
f k v
is None
then k
is not in the result,f k v
is Some v'
then the binding (k, v')
is in the output map.For example, the following function on maps whose values are lists
filter_map
+ (fun _k li -> match li with [] -> None | _::tl -> Some tl)
+ m
drops all bindings of m
whose value is an empty list, and pops the first element of each value that is non-empty.
partition ~f m
returns a pair of maps (m1, m2)
, where m1
contains all the bindings of m
that satisfy the predicate f
, and m2
is the map with all the bindings of m
that do not satisfy f
.
split x m
returns a triple (l, data, r)
, where l
is the map with all the bindings of m
whose key is strictly less than x
; r
is the map with all the bindings of m
whose key is strictly greater than x
; data
is None
if m
contains no binding for x
, or Some v
if m
binds v
to x
.
val is_empty : 'a t -> bool
Test whether a map is empty or not.
mem x m
returns true
if m
contains a binding for x
, and false
otherwise.
equal ~cmp m1 m2
tests whether the maps m1
and m2
are equal, that is, contain equal keys and associate them with equal data. cmp
is the equality predicate used to compare the data associated with the keys.
Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps.
for_all ~f m
checks if all the bindings of the map satisfy the predicate f
.
exists ~f m
checks if at least one binding of the map satisfies the predicate f
.
of_list bs
adds the bindings of bs
to the empty map, in list order (if a key is bound twice in bs
the last one takes over).
Iterate on the whole map, in descending order of keys
to_seq_from k m
iterates on a subset of the bindings of m
, in ascending order of keys, from key k
or above.
MoreLabels_alerting.Map
Association tables over ordered types.
This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map.
For instance:
module IntPairs =
+ struct
+ type t = int * int
+ let compare (x0,y0) (x1,y1) =
+ match Stdlib.compare x0 x1 with
+ 0 -> Stdlib.compare y0 y1
+ | c -> c
+ end
+
+module PairsMap = Map.Make(IntPairs)
+
+let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world")
This creates a new module PairsMap
, with a new type 'a PairsMap.t
of maps from int * int
to 'a
. In this example, m
contains string
values so its type is string PairsMap.t
.
module type OrderedType = sig ... end
Input signature of the functor Make
.
Map.OrderedType
Input signature of the functor Make
.
A total ordering function over the keys. This is a two-argument function f
such that f e1 e2
is zero if the keys e1
and e2
are equal, f e1 e2
is strictly negative if e1
is smaller than e2
, and f e1 e2
is strictly positive if e1
is greater than e2
. Example: a suitable ordering function is the generic structural comparison function Stdlib.compare
.
Map.S
Output signature of the functor Make
.
val empty : 'a t
The empty map.
add ~key ~data m
returns a map containing the same bindings as m
, plus a binding of key
to data
. If key
was already bound in m
to a value that is physically equal to data
, m
is returned unchanged (the result of the function is then physically equal to m
). Otherwise, the previous binding of key
in m
disappears.
add_to_list ~key ~data m
is m
with key
mapped to l
such that l
is data :: Map.find key m
if key
was bound in m
and [v]
otherwise.
update ~key ~f m
returns a map containing the same bindings as m
, except for the binding of key
. Depending on the value of y
where y
is f (find_opt key m)
, the binding of key
is added, removed or updated. If y
is None
, the binding is removed if it exists; otherwise, if y
is Some z
then key
is associated to z
in the resulting map. If key
was already bound in m
to a value that is physically equal to z
, m
is returned unchanged (the result of the function is then physically equal to m
).
singleton x y
returns the one-element map that contains a binding y
for x
.
remove x m
returns a map containing the same bindings as m
, except for x
which is unbound in the returned map. If x
was not in m
, m
is returned unchanged (the result of the function is then physically equal to m
).
merge ~f m1 m2
computes a map whose keys are a subset of the keys of m1
and of m2
. The presence of each such binding, and the corresponding value, is determined with the function f
. In terms of the find_opt
operation, we have find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)
for any key x
, provided that f x None None = None
.
union ~f m1 m2
computes a map whose keys are a subset of the keys of m1
and of m2
. When the same binding is defined in both arguments, the function f
is used to combine them. This is a special case of merge
: union f m1 m2
is equivalent to merge f' m1 m2
, where
f' _key None None = None
f' _key (Some v) None = Some v
f' _key None (Some v) = Some v
f' key (Some v1) (Some v2) = f key v1 v2
val cardinal : 'a t -> int
Return the number of bindings of a map.
Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering Ord.compare
, where Ord
is the argument given to Map.Make
.
Return the binding with the smallest key in a given map (with respect to the Ord.compare
ordering), or raise Not_found
if the map is empty.
Return the binding with the smallest key in the given map (with respect to the Ord.compare
ordering), or None
if the map is empty.
Same as min_binding
, but returns the binding with the largest key in the given map.
Same as min_binding_opt
, but returns the binding with the largest key in the given map.
Return one binding of the given map, or raise Not_found
if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
Return one binding of the given map, or None
if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
find x m
returns the current value of x
in m
, or raises Not_found
if no binding for x
exists.
find_opt x m
returns Some v
if the current value of x
in m
is v
, or None
if no binding for x
exists.
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.
For example, find_first (fun k -> Ord.compare k x >= 0) m
will return the first binding k, v
of m
where Ord.compare k x >= 0
(intuitively: k >= x
), or raise Not_found
if x
is greater than any element of m
.
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.
find_last ~f m
, where f
is a monotonically decreasing function, returns the binding of m
with the highest key k
such that f k
, or raises Not_found
if no such key exists.
find_last_opt ~f m
, where f
is a monotonically decreasing function, returns an option containing the binding of m
with the highest key k
such that f k
, or None
if no such key exists.
iter ~f m
applies f
to all bindings in map m
. f
receives the key as first argument, and the associated value as second argument. The bindings are passed to f
in increasing order with respect to the ordering over the type of the keys.
fold ~f m ~init
computes (f kN dN ... (f k1 d1 init)...)
, where k1 ... kN
are the keys of all bindings in m
(in increasing order), and d1 ... dN
are the associated data.
map ~f m
returns a map with same domain as m
, where the associated value a
of all bindings of m
has been replaced by the result of the application of f
to a
. The bindings are passed to f
in increasing order with respect to the ordering over the type of the keys.
Same as map
, but the function receives as arguments both the key and the associated value for each binding of the map.
filter ~f m
returns the map with all the bindings in m
that satisfy predicate p
. If every binding in m
satisfies f
, m
is returned unchanged (the result of the function is then physically equal to m
)
filter_map ~f m
applies the function f
to every binding of m
, and builds a map from the results. For each binding (k, v)
in the input map:
f k v
is None
then k
is not in the result,f k v
is Some v'
then the binding (k, v')
is in the output map.For example, the following function on maps whose values are lists
filter_map
+ (fun _k li -> match li with [] -> None | _::tl -> Some tl)
+ m
drops all bindings of m
whose value is an empty list, and pops the first element of each value that is non-empty.
partition ~f m
returns a pair of maps (m1, m2)
, where m1
contains all the bindings of m
that satisfy the predicate f
, and m2
is the map with all the bindings of m
that do not satisfy f
.
split x m
returns a triple (l, data, r)
, where l
is the map with all the bindings of m
whose key is strictly less than x
; r
is the map with all the bindings of m
whose key is strictly greater than x
; data
is None
if m
contains no binding for x
, or Some v
if m
binds v
to x
.
val is_empty : 'a t -> bool
Test whether a map is empty or not.
mem x m
returns true
if m
contains a binding for x
, and false
otherwise.
equal ~cmp m1 m2
tests whether the maps m1
and m2
are equal, that is, contain equal keys and associate them with equal data. cmp
is the equality predicate used to compare the data associated with the keys.
Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps.
for_all ~f m
checks if all the bindings of the map satisfy the predicate f
.
exists ~f m
checks if at least one binding of the map satisfies the predicate f
.
of_list bs
adds the bindings of bs
to the empty map, in list order (if a key is bound twice in bs
the last one takes over).
Iterate on the whole map, in descending order of keys
to_seq_from k m
iterates on a subset of the bindings of m
, in ascending order of keys, from key k
or above.
Make.Ord
A total ordering function over the set elements. This is a two-argument function f
such that f e1 e2
is zero if the elements e1
and e2
are equal, f e1 e2
is strictly negative if e1
is smaller than e2
, and f e1 e2
is strictly positive if e1
is greater than e2
. Example: a suitable ordering function is the generic structural comparison function Stdlib.compare
.
Set.Make
Functor building an implementation of the set structure given a totally ordered type.
module Ord : OrderedType
type elt = Ord.t
The type of the set elements.
val empty : t
The empty set.
add x s
returns a set containing all elements of s
, plus x
. If x
was already in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
remove x s
returns a set containing all elements of s
, except x
. If x
was not in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
val cardinal : t -> int
Return the number of elements of a set.
Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering Ord.compare
, where Ord
is the argument given to Set.Make
.
Return the smallest element of the given set (with respect to the Ord.compare
ordering), or raise Not_found
if the set is empty.
Return the smallest element of the given set (with respect to the Ord.compare
ordering), or None
if the set is empty.
Same as min_elt_opt
, but returns the largest element of the given set.
Return one element of the given set, or raise Not_found
if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
Return one element of the given set, or None
if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
find x s
returns the element of s
equal to x
(according to Ord.compare
), or raise Not_found
if no such element exists.
find_opt x s
returns the element of s
equal to x
(according to Ord.compare
), or None
if no such element exists.
find_first ~f s
, where f
is a monotonically increasing function, returns the lowest element e
of s
such that f e
, or raises Not_found
if no such element exists.
For example, find_first (fun e -> Ord.compare e x >= 0) s
will return the first element e
of s
where Ord.compare e x >= 0
(intuitively: e >= x
), or raise Not_found
if x
is greater than any element of s
.
find_first_opt ~f s
, where f
is a monotonically increasing function, returns an option containing the lowest element e
of s
such that f e
, or None
if no such element exists.
find_last ~f s
, where f
is a monotonically decreasing function, returns the highest element e
of s
such that f e
, or raises Not_found
if no such element exists.
find_last_opt ~f s
, where f
is a monotonically decreasing function, returns an option containing the highest element e
of s
such that f e
, or None
if no such element exists.
iter ~f s
applies f
in turn to all elements of s
. The elements of s
are presented to f
in increasing order with respect to the ordering over the type of the elements.
fold ~f s init
computes (f xN ... (f x2 (f x1 init))...)
, where x1 ... xN
are the elements of s
, in increasing order.
map ~f s
is the set whose elements are f a0
,f a1
... f
+ aN
, where a0
,a1
...aN
are the elements of s
.
The elements are passed to f
in increasing order with respect to the ordering over the type of the elements.
If no element of s
is changed by f
, s
is returned unchanged. (If each output of f
is physically equal to its input, the returned set is physically equal to s
.)
filter ~f s
returns the set of all elements in s
that satisfy predicate f
. If f
satisfies every element in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
filter_map ~f s
returns the set of all v
such that f x = Some v
for some element x
of s
.
For example,
filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s
is the set of halves of the even elements of s
.
If no element of s
is changed or dropped by f
(if f x = Some x
for each element x
), then s
is returned unchanged: the result of the function is then physically equal to s
.
partition ~f s
returns a pair of sets (s1, s2)
, where s1
is the set of all the elements of s
that satisfy the predicate f
, and s2
is the set of all the elements of s
that do not satisfy f
.
split x s
returns a triple (l, present, r)
, where l
is the set of elements of s
that are strictly less than x
; r
is the set of elements of s
that are strictly greater than x
; present
is false
if s
contains no element equal to x
, or true
if s
contains an element equal to x
.
val is_empty : t -> bool
Test whether a set is empty or not.
equal s1 s2
tests whether the sets s1
and s2
are equal, that is, contain equal elements.
Total ordering between sets. Can be used as the ordering function for doing sets of sets.
for_all ~f s
checks if all elements of the set satisfy the predicate f
.
exists ~f s
checks if at least one element of the set satisfies the predicate f
.
of_list l
creates a set from a list of elements. This is usually more efficient than folding add
over the list, except perhaps for lists with many duplicated elements.
to_seq_from x s
iterates on a subset of the elements of s
in ascending order, from x
or above.
MoreLabels_alerting.Set
Sets over ordered types.
This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance.
The Make
functor constructs implementations for any type, given a compare
function. For instance:
module IntPairs =
+ struct
+ type t = int * int
+ let compare (x0,y0) (x1,y1) =
+ match Stdlib.compare x0 x1 with
+ 0 -> Stdlib.compare y0 y1
+ | c -> c
+ end
+
+module PairsSet = Set.Make(IntPairs)
+
+let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13))
This creates a new module PairsSet
, with a new type PairsSet.t
of sets of int * int
.
module type OrderedType = sig ... end
Input signature of the functor Make
.
Set.OrderedType
Input signature of the functor Make
.
A total ordering function over the set elements. This is a two-argument function f
such that f e1 e2
is zero if the elements e1
and e2
are equal, f e1 e2
is strictly negative if e1
is smaller than e2
, and f e1 e2
is strictly positive if e1
is greater than e2
. Example: a suitable ordering function is the generic structural comparison function Stdlib.compare
.
Set.S
Output signature of the functor Make
.
val empty : t
The empty set.
add x s
returns a set containing all elements of s
, plus x
. If x
was already in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
remove x s
returns a set containing all elements of s
, except x
. If x
was not in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
val cardinal : t -> int
Return the number of elements of a set.
Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering Ord.compare
, where Ord
is the argument given to Set.Make
.
Return the smallest element of the given set (with respect to the Ord.compare
ordering), or raise Not_found
if the set is empty.
Return the smallest element of the given set (with respect to the Ord.compare
ordering), or None
if the set is empty.
Same as min_elt_opt
, but returns the largest element of the given set.
Return one element of the given set, or raise Not_found
if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
Return one element of the given set, or None
if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
find x s
returns the element of s
equal to x
(according to Ord.compare
), or raise Not_found
if no such element exists.
find_opt x s
returns the element of s
equal to x
(according to Ord.compare
), or None
if no such element exists.
find_first ~f s
, where f
is a monotonically increasing function, returns the lowest element e
of s
such that f e
, or raises Not_found
if no such element exists.
For example, find_first (fun e -> Ord.compare e x >= 0) s
will return the first element e
of s
where Ord.compare e x >= 0
(intuitively: e >= x
), or raise Not_found
if x
is greater than any element of s
.
find_first_opt ~f s
, where f
is a monotonically increasing function, returns an option containing the lowest element e
of s
such that f e
, or None
if no such element exists.
find_last ~f s
, where f
is a monotonically decreasing function, returns the highest element e
of s
such that f e
, or raises Not_found
if no such element exists.
find_last_opt ~f s
, where f
is a monotonically decreasing function, returns an option containing the highest element e
of s
such that f e
, or None
if no such element exists.
iter ~f s
applies f
in turn to all elements of s
. The elements of s
are presented to f
in increasing order with respect to the ordering over the type of the elements.
fold ~f s init
computes (f xN ... (f x2 (f x1 init))...)
, where x1 ... xN
are the elements of s
, in increasing order.
map ~f s
is the set whose elements are f a0
,f a1
... f
+ aN
, where a0
,a1
...aN
are the elements of s
.
The elements are passed to f
in increasing order with respect to the ordering over the type of the elements.
If no element of s
is changed by f
, s
is returned unchanged. (If each output of f
is physically equal to its input, the returned set is physically equal to s
.)
filter ~f s
returns the set of all elements in s
that satisfy predicate f
. If f
satisfies every element in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
filter_map ~f s
returns the set of all v
such that f x = Some v
for some element x
of s
.
For example,
filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s
is the set of halves of the even elements of s
.
If no element of s
is changed or dropped by f
(if f x = Some x
for each element x
), then s
is returned unchanged: the result of the function is then physically equal to s
.
partition ~f s
returns a pair of sets (s1, s2)
, where s1
is the set of all the elements of s
that satisfy the predicate f
, and s2
is the set of all the elements of s
that do not satisfy f
.
split x s
returns a triple (l, present, r)
, where l
is the set of elements of s
that are strictly less than x
; r
is the set of elements of s
that are strictly greater than x
; present
is false
if s
contains no element equal to x
, or true
if s
contains an element equal to x
.
val is_empty : t -> bool
Test whether a set is empty or not.
equal s1 s2
tests whether the sets s1
and s2
are equal, that is, contain equal elements.
Total ordering between sets. Can be used as the ordering function for doing sets of sets.
for_all ~f s
checks if all elements of the set satisfy the predicate f
.
exists ~f s
checks if at least one element of the set satisfies the predicate f
.
of_list l
creates a set from a list of elements. This is usually more efficient than folding add
over the list, except perhaps for lists with many duplicated elements.
to_seq_from x s
iterates on a subset of the elements of s
in ascending order, from x
or above.
Stdlib_alerts.MoreLabels_alerting
Printexc_alerting.Slot
type t = backtrace_slot
val is_raise : t -> bool
is_raise slot
is true
when slot
refers to a raising point in the code, and false
when it comes from a simple function call.
val is_inline : t -> bool
is_inline slot
is true
when slot
refers to a call that got inlined by the compiler, and false
when it comes from any other context.
location slot
returns the location information of the slot, if available, and None
otherwise.
Some possible reasons for failing to return a location are as follow:
-g
)val name : t -> string option
name slot
returns the name of the function or definition enclosing the location referred to by the slot.
name slot
returns None if the name is unavailable, which may happen for the same reasons as location
returning None.
val format : int -> t -> string option
format pos slot
returns the string representation of slot
as raw_backtrace_to_string
would format it, assuming it is the pos
-th element of the backtrace: the 0
-th element is pretty-printed differently than the others.
Whole-backtrace printing functions also skip some uninformative slots; in that case, format pos slot
returns None
.
Stdlib_alerts.Printexc_alerting
include sig ... end
Printexc.to_string_default e
returns a string representation of the exception e
, ignoring all registered exception printers.
Printexc.to_string e
returns a string representation of the exception e
.
Printexc.print fn x
applies fn
to x
and returns the result. If the evaluation of fn x
raises any exception, the name of the exception is printed on standard error output, and the exception is raised again. The typical use is to catch and report exceptions that escape a function application.
Printexc.catch fn x
is similar to Printexc.print
, but aborts the program with exit code 2 after printing the uncaught exception. This function is deprecated: the runtime system is now able to print uncaught exceptions as precisely as Printexc.catch
does. Moreover, calling Printexc.catch
makes it harder to track the location of the exception using the debugger or the stack backtrace facility. So, do not use Printexc.catch
in new code.
Printexc.print_backtrace oc
prints an exception backtrace on the output channel oc
. The backtrace lists the program locations where the most-recently raised exception was raised and where it was propagated through function calls.
If the call is not inside an exception handler, the returned backtrace is unspecified. If the call is after some exception-catching code (before in the handler, or in a when-guard during the matching of the exception handler), the backtrace may correspond to a later exception than the handled one.
Printexc.get_backtrace ()
returns a string containing the same exception backtrace that Printexc.print_backtrace
would print. Same restriction usage than print_backtrace
.
Printexc.record_backtrace b
turns recording of exception backtraces on (if b = true
) or off (if b = false
). Initially, backtraces are not recorded, unless the b
flag is given to the program through the OCAMLRUNPARAM
variable.
Printexc.backtrace_status()
returns true
if exception backtraces are currently recorded, false
if not.
Printexc.register_printer fn
registers fn
as an exception printer. The printer should return None
or raise an exception if it does not know how to convert the passed exception, and Some
+ s
with s
the resulting string if it can convert the passed exception. Exceptions raised by the printer are ignored.
When converting an exception into a string, the printers will be invoked in the reverse order of their registrations, until a printer returns a Some s
value (if no such printer exists, the runtime will use a generic printer).
When using this mechanism, one should be aware that an exception backtrace is attached to the thread that saw it raised, rather than to the exception itself. Practically, it means that the code related to fn
should not use the backtrace if it has itself raised an exception before.
Printexc.use_printers e
returns None
if there are no registered printers and Some s
with else as the resulting string otherwise.
The type raw_backtrace
stores a backtrace in a low-level format, which can be converted to usable form using raw_backtrace_entries
and backtrace_slots_of_raw_entry
below.
Converting backtraces to backtrace_slot
s is slower than capturing the backtraces. If an application processes many backtraces, it can be useful to use raw_backtrace
to avoid or delay conversion.
Raw backtraces cannot be marshalled. If you need marshalling, you should use the array returned by the backtrace_slots
function of the next section.
A raw_backtrace_entry
is an element of a raw_backtrace
.
Each raw_backtrace_entry
is an opaque integer, whose value is not stable between different programs, or even between different runs of the same binary.
A raw_backtrace_entry
can be converted to a usable form using backtrace_slots_of_raw_entry
below. Note that, due to inlining, a single raw_backtrace_entry
may convert to several backtrace_slot
s. Since the values of a raw_backtrace_entry
are not stable, they cannot be marshalled. If they are to be converted, the conversion must be done by the process that generated them.
Again due to inlining, there may be multiple distinct raw_backtrace_entry values that convert to equal backtrace_slot
s. However, if two raw_backtrace_entry
s are equal as integers, then they represent the same backtrace_slot
s.
val raw_backtrace_entries : raw_backtrace -> raw_backtrace_entry array
val get_raw_backtrace : unit -> raw_backtrace
Printexc.get_raw_backtrace ()
returns the same exception backtrace that Printexc.print_backtrace
would print, but in a raw format. Same restriction usage than print_backtrace
.
val print_raw_backtrace : Stdlib.out_channel -> raw_backtrace -> unit
Print a raw backtrace in the same format Printexc.print_backtrace
uses.
val raw_backtrace_to_string : raw_backtrace -> string
Return a string from a raw backtrace, in the same format Printexc.get_backtrace
uses.
val raise_with_backtrace : exn -> raw_backtrace -> 'a
Reraise the exception using the given raw_backtrace for the origin of the exception
val get_callstack : int -> raw_backtrace
Printexc.get_callstack n
returns a description of the top of the call stack on the current program point (for the current thread), with at most n
entries. (Note: this function is not related to exceptions at all, despite being part of the Printexc
module.)
val default_uncaught_exception_handler : exn -> raw_backtrace -> unit
Printexc.default_uncaught_exception_handler
prints the exception and backtrace on standard error output.
val set_uncaught_exception_handler : (exn -> raw_backtrace -> unit) -> unit
Printexc.set_uncaught_exception_handler fn
registers fn
as the handler for uncaught exceptions. The default handler is Printexc.default_uncaught_exception_handler
.
Note that when fn
is called all the functions registered with Stdlib.at_exit
have already been called. Because of this you must make sure any output channel fn
writes on is flushed.
Also note that exceptions raised by user code in the interactive toplevel are not passed to this function as they are caught by the toplevel itself.
If fn
raises an exception, both the exceptions passed to fn
and raised by fn
will be printed with their respective backtrace.
val backtrace_slots : raw_backtrace -> backtrace_slot array option
Returns the slots of a raw backtrace, or None
if none of them contain useful information.
In the return array, the slot at index 0
corresponds to the most recent function call, raise, or primitive get_backtrace
call in the trace.
Some possible reasons for returning None
are as follow:
-g
)ocamlc -g
)val backtrace_slots_of_raw_entry :
+ raw_backtrace_entry ->
+ backtrace_slot array option
Returns the slots of a single raw backtrace entry, or None
if this entry lacks debug information.
Slots are returned in the same order as backtrace_slots
: the slot at index 0
is the most recent call, raise, or primitive, and subsequent slots represent callers.
The type of location information found in backtraces. start_char
and end_char
are positions relative to the beginning of the line.
module Slot : sig ... end
This type is used to iterate over the slots of a raw_backtrace
. For most purposes, backtrace_slots_of_raw_entry
is easier to use.
Like raw_backtrace_entry
, values of this type are process-specific and must absolutely not be marshalled, and are unsafe to use for this reason (marshalling them may not fail, but un-marshalling and using the result will result in undefined behavior).
Elements of this type can still be compared and hashed: when two elements are equal, then they represent the same source location (the converse is not necessarily true in presence of inlining, for example).
val raw_backtrace_length : raw_backtrace -> int
raw_backtrace_length bckt
returns the number of slots in the backtrace bckt
.
val get_raw_backtrace_slot : raw_backtrace -> int -> raw_backtrace_slot
get_raw_backtrace_slot bckt pos
returns the slot in position pos
in the backtrace bckt
.
val convert_raw_backtrace_slot : raw_backtrace_slot -> backtrace_slot
Extracts the user-friendly backtrace_slot
from a low-level raw_backtrace_slot
.
val get_raw_backtrace_next_slot :
+ raw_backtrace_slot ->
+ raw_backtrace_slot option
get_raw_backtrace_next_slot slot
returns the next slot inlined, if any.
Sample code to iterate over all frames (inlined and non-inlined):
(* Iterate over inlined frames *)
+let rec iter_raw_backtrace_slot f slot =
+ f slot;
+ match get_raw_backtrace_next_slot slot with
+ | None -> ()
+ | Some slot' -> iter_raw_backtrace_slot f slot'
+
+(* Iterate over stack frames *)
+let iter_raw_backtrace f bt =
+ for i = 0 to raw_backtrace_length bt - 1 do
+ iter_raw_backtrace_slot f (get_raw_backtrace_slot bt i)
+ done
Printexc.exn_slot_id
returns an integer which uniquely identifies the constructor used to create the exception value exn
(in the current runtime).
Printexc.exn_slot_name exn
returns the internal name of the constructor used to create the exception value exn
.
Stdlib_alerts.Printf_alerting
include sig ... end
Same as Printf.fprintf
, but instead of printing on an output channel, return a string containing the result of formatting the arguments.
Same as sprintf
above, but instead of returning the string, passes it to the first argument.
fprintf outchan format arg1 ... argN
formats the arguments arg1
to argN
according to the format string format
, and outputs the resulting string on the channel outchan
.
The format string is a character string which contains two types of objects: plain characters, which are simply copied to the output channel, and conversion specifications, each of which causes conversion and printing of arguments.
Conversion specifications have the following form:
% [flags] [width] [.precision] type
In short, a conversion specification consists in the %
character, followed by optional modifiers and a type which is made of one or two characters.
The types and their meanings are:
d
, i
: convert an integer argument to signed decimal. The flag #
adds underscores to large values for readability.u
, n
, l
, L
, or N
: convert an integer argument to unsigned decimal. Warning: n
, l
, L
, and N
are used for scanf
, and should not be used for printf
. The flag #
adds underscores to large values for readability.x
: convert an integer argument to unsigned hexadecimal, using lowercase letters. The flag #
adds a 0x
prefix to non zero values.X
: convert an integer argument to unsigned hexadecimal, using uppercase letters. The flag #
adds a 0X
prefix to non zero values.o
: convert an integer argument to unsigned octal. The flag #
adds a 0
prefix to non zero values.s
: insert a string argument.S
: convert a string argument to OCaml syntax (double quotes, escapes).c
: insert a character argument.C
: convert a character argument to OCaml syntax (single quotes, escapes).f
: convert a floating-point argument to decimal notation, in the style dddd.ddd
.F
: convert a floating-point argument to OCaml syntax (dddd.
or dddd.ddd
or d.ddd e+-dd
). Converts to hexadecimal with the #
flag (see h
).e
or E
: convert a floating-point argument to decimal notation, in the style d.ddd e+-dd
(mantissa and exponent).g
or G
: convert a floating-point argument to decimal notation, in style f
or e
, E
(whichever is more compact). Moreover, any trailing zeros are removed from the fractional part of the result and the decimal-point character is removed if there is no fractional part remaining.h
or H
: convert a floating-point argument to hexadecimal notation, in the style 0xh.hhhh p+-dd
(hexadecimal mantissa, exponent in decimal and denotes a power of 2).B
: convert a boolean argument to the string true
or false
b
: convert a boolean argument (deprecated; do not use in new programs).ld
, li
, lu
, lx
, lX
, lo
: convert an int32
argument to the format specified by the second letter (decimal, hexadecimal, etc).nd
, ni
, nu
, nx
, nX
, no
: convert a nativeint
argument to the format specified by the second letter.Ld
, Li
, Lu
, Lx
, LX
, Lo
: convert an int64
argument to the format specified by the second letter.a
: user-defined printer. Take two arguments and apply the first one to outchan
(the current output channel) and to the second argument. The first argument must therefore have type out_channel -> 'b -> unit
and the second 'b
. The output produced by the function is inserted in the output of fprintf
at the current point.t
: same as %a
, but take only one argument (with type out_channel -> unit
) and apply it to outchan
.\{ fmt %\}
: convert a format string argument to its type digest. The argument must have the same type as the internal format string fmt
.( fmt %)
: format string substitution. Take a format string argument and substitute it to the internal format string fmt
to print following arguments. The argument must have the same type as the internal format string fmt
.!
: take no argument and flush the output.%
: take no argument and output one %
character.\@
: take no argument and output one \@
character.,
: take no argument and output nothing: a no-op delimiter for conversion specifications.The optional flags
are:
-
: left-justify the output (default is right justification).0
: for numerical conversions, pad with zeroes instead of spaces.+
: for signed numerical conversions, prefix number with a +
sign if positive.#
: request an alternate formatting style for the integer types and the floating-point type F
.The optional width
is an integer indicating the minimal width of the result. For instance, %6d
prints an integer, prefixing it with spaces to fill at least 6 characters.
The optional precision
is a dot .
followed by an integer indicating how many digits follow the decimal point in the %f
, %e
, %E
, %h
, and %H
conversions or the maximum number of significant digits to appear for the %F
, %g
and %G
conversions. For instance, %.4f
prints a float
with 4 fractional digits.
The integer in a width
or precision
can also be specified as *
, in which case an extra integer argument is taken to specify the corresponding width
or precision
. This integer argument precedes immediately the argument to print. For instance, %.*f
prints a float
with as many fractional digits as the value of the argument given before the float.
Same as Printf.fprintf
, but output on stdout
.
Same as Printf.fprintf
, but output on stderr
.
Same as Printf.fprintf
, but does not print anything. Useful to ignore some material when conditionally printing.
val kfprintf :
+ (Stdlib.out_channel -> 'd) ->
+ Stdlib.out_channel ->
+ ('a, Stdlib.out_channel, unit, 'd) Stdlib.format4 ->
+ 'a
Same as fprintf
, but instead of returning immediately, passes the out channel to its first argument at the end of printing.
Same as kfprintf
above, but does not print anything. Useful to ignore some material when conditionally printing.
Same as Printf.fprintf
, but instead of printing on an output channel, append the formatted arguments to the given extensible buffer (see module Buffer
).
Same as Printf.bprintf
, but does not print anything. Useful to ignore some material when conditionally printing.
Scanf_alerting.Scanning
Stdlib_alerts.Scanf_alerting
module Scanning : sig ... end
include sig ... end
type ('a, 'b, 'c, 'd) scanner =
+ ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd, 'd) Stdlib.format6 ->
+ 'c
The type of formatted input scanners: ('a, 'b, 'c, 'd) scanner
is the type of a formatted input function that reads from some formatted input channel according to some format string; more precisely, if scan
is some formatted input function, then scan
+ ic fmt f
applies f
to all the arguments specified by format string fmt
, when scan
has read those arguments from the Scanning.in_channel
formatted input channel ic
.
For instance, the Scanf.scanf
function below has type ('a, 'b, 'c, 'd) scanner
, since it is a formatted input function that reads from Scanning.stdin
: scanf fmt f
applies f
to the arguments specified by fmt
, reading those arguments from Stdlib.stdin
as expected.
If the format fmt
has some %r
indications, the corresponding formatted input functions must be provided before receiver function f
. For instance, if read_elem
is an input function for values of type t
, then bscanf ic "%r;" read_elem f
reads a value v
of type t
followed by a ';'
character, and returns f v
.
type ('a, 'b, 'c, 'd) scanner_opt =
+ ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd option, 'd) Stdlib.format6 ->
+ 'c
When the input can not be read according to the format string specification, formatted input functions typically raise exception Scan_failure
.
val sscanf : string -> ('a, 'b, 'c, 'd) scanner
Same as Scanf.bscanf
, but reads from the given string.
val sscanf_opt : string -> ('a, 'b, 'c, 'd) scanner_opt
Same as Scanf.sscanf
, but returns None
in case of scanning failure.
val ksscanf :
+ string ->
+ (Scanning.in_channel -> exn -> 'd) ->
+ ('a, 'b, 'c, 'd) scanner
Same as Scanf.kscanf
but reads from the given string.
val sscanf_format :
+ string ->
+ ('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6 ->
+ (('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6 -> 'g) ->
+ 'g
Same as Scanf.bscanf_format
, but reads from the given string.
val format_from_string :
+ string ->
+ ('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6 ->
+ ('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6
format_from_string s fmt
converts a string argument to a format string, according to the given format string fmt
.
unescaped s
return a copy of s
with escape sequences (according to the lexical conventions of OCaml) replaced by their corresponding special characters. More precisely, Scanf.unescaped
has the following property: for all string s
, Scanf.unescaped (String.escaped s) = s
.
Always return a copy of the argument, even if there is no escape sequence in the argument.
val bscanf : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner
val bscanf_opt : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner_opt
Same as Scanf.bscanf
, but returns None
in case of scanning failure.
val scanf : ('a, 'b, 'c, 'd) scanner
Same as Scanf.bscanf
, but reads from the predefined formatted input channel Scanf.Scanning.stdin
that is connected to Stdlib.stdin
.
val scanf_opt : ('a, 'b, 'c, 'd) scanner_opt
Same as Scanf.scanf
, but returns None
in case of scanning failure.
val kscanf :
+ Scanning.in_channel ->
+ (Scanning.in_channel -> exn -> 'd) ->
+ ('a, 'b, 'c, 'd) scanner
Same as Scanf.bscanf
, but takes an additional function argument ef
that is called in case of error: if the scanning process or some conversion fails, the scanning function aborts and calls the error handling function ef
with the formatted input channel and the exception that aborted the scanning process as arguments.
val bscanf_format :
+ Scanning.in_channel ->
+ ('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6 ->
+ (('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6 -> 'g) ->
+ 'g
bscanf_format ic fmt f
reads a format string token from the formatted input channel ic
, according to the given format string fmt
, and applies f
to the resulting format string value.
Stdlib_alerts.Seq_alerting
include sig ... end
type 'a t = unit -> 'a node
A sequence xs
of type 'a t
is a delayed list of elements of type 'a
. Such a sequence is queried by performing a function application xs()
. This function application returns a node, allowing the caller to determine whether the sequence is empty or nonempty, and in the latter case, to obtain its head and tail.
A node is either Nil
, which means that the sequence is empty, or Cons (x, xs)
, which means that x
is the first element of the sequence and that xs
is the remainder of the sequence.
val is_empty : 'a t -> bool
is_empty xs
determines whether the sequence xs
is empty.
It is recommended that the sequence xs
be persistent. Indeed, is_empty xs
demands the head of the sequence xs
, so, if xs
is ephemeral, it may be the case that xs
cannot be used any more after this call has taken place.
If xs
is empty, then uncons xs
is None
.
If xs
is nonempty, then uncons xs
is Some (x, ys)
where x
is the head of the sequence and ys
its tail.
val length : 'a t -> int
length xs
is the length of the sequence xs
.
The sequence xs
must be finite.
val iter : ('a -> unit) -> 'a t -> unit
iter f xs
invokes f x
successively for every element x
of the sequence xs
, from left to right.
It terminates only if the sequence xs
is finite.
val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc
fold_left f _ xs
invokes f _ x
successively for every element x
of the sequence xs
, from left to right.
An accumulator of type 'a
is threaded through the calls to f
.
It terminates only if the sequence xs
is finite.
val iteri : (int -> 'a -> unit) -> 'a t -> unit
iteri f xs
invokes f i x
successively for every element x
located at index i
in the sequence xs
.
It terminates only if the sequence xs
is finite.
iteri f xs
is equivalent to iter (fun (i, x) -> f i x) (zip (ints 0) xs)
.
val fold_lefti : ('acc -> int -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc
fold_lefti f _ xs
invokes f _ i x
successively for every element x
located at index i
of the sequence xs
.
An accumulator of type 'b
is threaded through the calls to f
.
It terminates only if the sequence xs
is finite.
fold_lefti f accu xs
is equivalent to fold_left (fun accu (i, x) -> f accu i x) accu (zip (ints 0) xs)
.
val for_all : ('a -> bool) -> 'a t -> bool
for_all p xs
determines whether all elements x
of the sequence xs
satisfy p x
.
The sequence xs
must be finite.
val exists : ('a -> bool) -> 'a t -> bool
exists xs p
determines whether at least one element x
of the sequence xs
satisfies p x
.
The sequence xs
must be finite.
val find : ('a -> bool) -> 'a t -> 'a option
find p xs
returns Some x
, where x
is the first element of the sequence xs
that satisfies p x
, if there is such an element.
It returns None
if there is no such element.
The sequence xs
must be finite.
val find_index : ('a -> bool) -> 'a t -> int option
find_index p xs
returns Some i
, where i
is the index of the first element of the sequence xs
that satisfies p x
, if there is such an element.
It returns None
if there is no such element.
The sequence xs
must be finite.
val find_map : ('a -> 'b option) -> 'a t -> 'b option
find_map f xs
returns Some y
, where x
is the first element of the sequence xs
such that f x = Some _
, if there is such an element, and where y
is defined by f x = Some y
.
It returns None
if there is no such element.
The sequence xs
must be finite.
val find_mapi : (int -> 'a -> 'b option) -> 'a t -> 'b option
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
The sequence xs
must be finite.
iter2 f xs ys
invokes f x y
successively for every pair (x, y)
of elements drawn synchronously from the sequences xs
and ys
.
If the sequences xs
and ys
have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
Iteration terminates only if at least one of the sequences xs
and ys
is finite.
iter2 f xs ys
is equivalent to iter (fun (x, y) -> f x y) (zip xs ys)
.
fold_left2 f _ xs ys
invokes f _ x y
successively for every pair (x, y)
of elements drawn synchronously from the sequences xs
and ys
.
An accumulator of type 'a
is threaded through the calls to f
.
If the sequences xs
and ys
have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
Iteration terminates only if at least one of the sequences xs
and ys
is finite.
fold_left2 f accu xs ys
is equivalent to fold_left (fun accu (x, y) -> f accu x y) (zip xs ys)
.
for_all2 p xs ys
determines whether all pairs (x, y)
of elements drawn synchronously from the sequences xs
and ys
satisfy p x y
.
If the sequences xs
and ys
have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. In particular, if xs
or ys
is empty, then for_all2 p xs ys
is true. This is where for_all2
and equal
differ: equal eq xs ys
can be true only if xs
and ys
have the same length.
At least one of the sequences xs
and ys
must be finite.
for_all2 p xs ys
is equivalent to for_all (fun b -> b) (map2 p xs ys)
.
exists2 p xs ys
determines whether some pair (x, y)
of elements drawn synchronously from the sequences xs
and ys
satisfies p x y
.
If the sequences xs
and ys
have different lengths, then iteration must stop as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
At least one of the sequences xs
and ys
must be finite.
exists2 p xs ys
is equivalent to exists (fun b -> b) (map2 p xs ys)
.
Provided the function eq
defines an equality on elements, equal eq xs ys
determines whether the sequences xs
and ys
are pointwise equal.
At least one of the sequences xs
and ys
must be finite.
Provided the function cmp
defines a preorder on elements, compare cmp xs ys
compares the sequences xs
and ys
according to the lexicographic preorder.
For more details on comparison functions, see Array.sort
.
At least one of the sequences xs
and ys
must be finite.
val empty : 'a t
empty
is the empty sequence. It has no elements. Its length is 0.
val return : 'a -> 'a t
return x
is the sequence whose sole element is x
. Its length is 1.
cons x xs
is the sequence that begins with the element x
, followed with the sequence xs
.
Writing cons (f()) xs
causes the function call f()
to take place immediately. For this call to be delayed until the sequence is queried, one must instead write (fun () -> Cons(f(), xs))
.
val init : int -> (int -> 'a) -> 'a t
init n f
is the sequence f 0; f 1; ...; f (n-1)
.
n
must be nonnegative.
If desired, the infinite sequence f 0; f 1; ...
can be defined as map f (ints 0)
.
val unfold : ('b -> ('a * 'b) option) -> 'b -> 'a t
unfold
constructs a sequence out of a step function and an initial state.
If f u
is None
then unfold f u
is the empty sequence. If f u
is Some (x, u')
then unfold f u
is the nonempty sequence cons x (unfold f u')
.
For example, unfold (function [] -> None | h :: t -> Some (h, t)) l
is equivalent to List.to_seq l
.
val repeat : 'a -> 'a t
repeat x
is the infinite sequence where the element x
is repeated indefinitely.
repeat x
is equivalent to cycle (return x)
.
val forever : (unit -> 'a) -> 'a t
forever f
is an infinite sequence where every element is produced (on demand) by the function call f()
.
For instance, forever Random.bool
is an infinite sequence of random bits.
forever f
is equivalent to map f (repeat ())
.
cycle xs
is the infinite sequence that consists of an infinite number of repetitions of the sequence xs
.
If xs
is an empty sequence, then cycle xs
is empty as well.
Consuming (a prefix of) the sequence cycle xs
once can cause the sequence xs
to be consumed more than once. Therefore, xs
must be persistent.
val iterate : ('a -> 'a) -> 'a -> 'a t
iterate f x
is the infinite sequence whose elements are x
, f x
, f (f x)
, and so on.
In other words, it is the orbit of the function f
, starting at x
.
map f xs
is the image of the sequence xs
through the transformation f
.
If xs
is the sequence x0; x1; ...
then map f xs
is the sequence f x0; f x1; ...
.
mapi
is analogous to map
, but applies the function f
to an index and an element.
mapi f xs
is equivalent to map2 f (ints 0) xs
.
filter p xs
is the sequence of the elements x
of xs
that satisfy p x
.
In other words, filter p xs
is the sequence xs
, deprived of the elements x
such that p x
is false.
filter_map f xs
is the sequence of the elements y
such that f x = Some y
, where x
ranges over xs
.
filter_map f xs
is equivalent to map Option.get (filter Option.is_some (map f xs))
.
If xs
is a sequence [x0; x1; x2; ...]
, then scan f a0 xs
is a sequence of accumulators [a0; a1; a2; ...]
where a1
is f a0 x0
, a2
is f a1 x1
, and so on.
Thus, scan f a0 xs
is conceptually related to fold_left f a0 xs
. However, instead of performing an eager iteration and immediately returning the final accumulator, it returns a sequence of accumulators.
For instance, scan (+) 0
transforms a sequence of integers into the sequence of its partial sums.
If xs
has length n
then scan f a0 xs
has length n+1
.
take n xs
is the sequence of the first n
elements of xs
.
If xs
has fewer than n
elements, then take n xs
is equivalent to xs
.
n
must be nonnegative.
drop n xs
is the sequence xs
, deprived of its first n
elements.
If xs
has fewer than n
elements, then drop n xs
is empty.
n
must be nonnegative.
drop
is lazy: the first n+1
elements of the sequence xs
are demanded only when the first element of drop n xs
is demanded. For this reason, drop 1 xs
is not equivalent to tail xs
, which queries xs
immediately.
take_while p xs
is the longest prefix of the sequence xs
where every element x
satisfies p x
.
drop_while p xs
is the sequence xs
, deprived of the prefix take_while p xs
.
Provided the function eq
defines an equality on elements, group eq xs
is the sequence of the maximal runs of adjacent duplicate elements of the sequence xs
.
Every element of group eq xs
is a nonempty sequence of equal elements.
The concatenation concat (group eq xs)
is equal to xs
.
Consuming group eq xs
, and consuming the sequences that it contains, can cause xs
to be consumed more than once. Therefore, xs
must be persistent.
The sequence memoize xs
has the same elements as the sequence xs
.
Regardless of whether xs
is ephemeral or persistent, memoize xs
is persistent: even if it is queried several times, xs
is queried at most once.
The construction of the sequence memoize xs
internally relies on suspensions provided by the module Lazy
. These suspensions are not thread-safe. Therefore, the sequence memoize xs
must not be queried by multiple threads concurrently.
If xss
is a matrix (a sequence of rows), then transpose xss
is the sequence of the columns of the matrix xss
.
The rows of the matrix xss
are not required to have the same length.
The matrix xss
is not required to be finite (in either direction).
The matrix xss
must be persistent.
append xs ys
is the concatenation of the sequences xs
and ys
.
Its elements are the elements of xs
, followed by the elements of ys
.
If xss
is a sequence of sequences, then concat xss
is its concatenation.
If xss
is the sequence xs0; xs1; ...
then concat xss
is the sequence xs0 @ xs1 @ ...
.
concat_map f xs
is equivalent to concat (map f xs)
.
concat_map
is an alias for flat_map
.
zip xs ys
is the sequence of pairs (x, y)
drawn synchronously from the sequences xs
and ys
.
If the sequences xs
and ys
have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
zip xs ys
is equivalent to map2 (fun a b -> (a, b)) xs ys
.
map2 f xs ys
is the sequence of the elements f x y
, where the pairs (x, y)
are drawn synchronously from the sequences xs
and ys
.
If the sequences xs
and ys
have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
map2 f xs ys
is equivalent to map (fun (x, y) -> f x y) (zip xs ys)
.
interleave xs ys
is the sequence that begins with the first element of xs
, continues with the first element of ys
, and so on.
When one of the sequences xs
and ys
is exhausted, interleave xs ys
continues with the rest of the other sequence.
If the sequences xs
and ys
are sorted according to the total preorder cmp
, then sorted_merge cmp xs ys
is the sorted sequence obtained by merging the sequences xs
and ys
.
For more details on comparison functions, see Array.sort
.
product xs ys
is the Cartesian product of the sequences xs
and ys
.
For every element x
of xs
and for every element y
of ys
, the pair (x, y)
appears once as an element of product xs ys
.
The order in which the pairs appear is unspecified.
The sequences xs
and ys
are not required to be finite.
The sequences xs
and ys
must be persistent.
The sequence map_product f xs ys
is the image through f
of the Cartesian product of the sequences xs
and ys
.
For every element x
of xs
and for every element y
of ys
, the element f x y
appears once as an element of map_product f xs ys
.
The order in which these elements appear is unspecified.
The sequences xs
and ys
are not required to be finite.
The sequences xs
and ys
must be persistent.
map_product f xs ys
is equivalent to map (fun (x, y) -> f x y) (product xs ys)
.
unzip
transforms a sequence of pairs into a pair of sequences.
unzip xs
is equivalent to (map fst xs, map snd xs)
.
Querying either of the sequences returned by unzip xs
causes xs
to be queried. Therefore, querying both of them causes xs
to be queried twice. Thus, xs
must be persistent and cheap. If that is not the case, use unzip (memoize xs)
.
partition_map f xs
returns a pair of sequences (ys, zs)
, where:
ys
is the sequence of the elements y
such that f x = Left y
, where x
ranges over xs
;zs
is the sequence of the elements z
such that f x = Right z
, where x
ranges over xs
.partition_map f xs
is equivalent to a pair of filter_map Either.find_left (map f xs)
and filter_map Either.find_right (map f xs)
.
Querying either of the sequences returned by partition_map f xs
causes xs
to be queried. Therefore, querying both of them causes xs
to be queried twice. Thus, xs
must be persistent and cheap. If that is not the case, use partition_map f (memoize xs)
.
partition p xs
returns a pair of the subsequence of the elements of xs
that satisfy p
and the subsequence of the elements of xs
that do not satisfy p
.
partition p xs
is equivalent to filter p xs, filter (fun x -> not (p x)) xs
.
Consuming both of the sequences returned by partition p xs
causes xs
to be consumed twice and causes the function f
to be applied twice to each element of the list. Therefore, f
should be pure and cheap. Furthermore, xs
should be persistent and cheap. If that is not the case, use partition p (memoize xs)
.
val of_dispenser : (unit -> 'a option) -> 'a t
of_dispenser it
is the sequence of the elements produced by the dispenser it
. It is an ephemeral sequence: it can be consumed at most once. If a persistent sequence is needed, use memoize (of_dispenser it)
.
val ints : int -> int t
ints i
is the infinite sequence of the integers beginning at i
and counting up.
The sequence once xs
has the same elements as the sequence xs
.
Regardless of whether xs
is ephemeral or persistent, once xs
is an ephemeral sequence: it can be queried at most once. If it (or a suffix of it) is queried more than once, then the exception Forced_twice
is raised. This can be useful, while debugging or testing, to ensure that a sequence is consumed at most once.
This exception is raised when a sequence returned by once
(or a suffix of it) is queried more than once.
val to_dispenser : 'a t -> unit -> 'a option
to_dispenser xs
is a fresh dispenser on the sequence xs
.
This dispenser has mutable internal state, which is not protected by a lock; so, it must not be used by several threads concurrently.
StdLabels_alerting.List
include sig ... end
Compare the lengths of two lists. compare_lengths l1 l2
is equivalent to compare (length l1) (length l2)
, except that the computation stops after reaching the end of the shortest list.
Compare the length of a list to an integer. compare_length_with l len
is equivalent to compare (length l) len
, except that the computation stops after at most len
iterations on the list.
is_empty l
is true if and only if l
has no elements. It is equivalent to compare_length_with l 0 = 0
.
Return the n
-th element of the given list. The first element (head of the list) is at position 0.
Return the n
-th element of the given list. The first element (head of the list) is at position 0. Return None
if the list is too short.
init ~len ~f
is [f 0; f 1; ...; f (len-1)]
, evaluated left to right.
append l0 l1
appends l1
to l0
. Same function as the infix operator @
.
rev_append l1 l2
reverses l1
and concatenates it with l2
. This is equivalent to (
rev
l1) @ l2
.
Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument + length of the longest sub-list).
Same as concat
. Not tail-recursive (length of the argument + length of the longest sub-list).
equal eq [a1; ...; an] [b1; ..; bm]
holds when the two input lists have the same length, and for each pair of elements ai
, bi
at the same position we have eq ai bi
.
Note: the eq
function may be called even if the lists have different length. If you know your equality function is costly, you may want to check compare_lengths
first.
compare cmp [a1; ...; an] [b1; ...; bm]
performs a lexicographic comparison of the two input lists, using the same 'a -> 'a -> int
interface as Stdlib.compare
:
a1 :: l1
is smaller than a2 :: l2
(negative result) if a1
is smaller than a2
, or if they are equal (0 result) and l1
is smaller than l2
[]
is strictly smaller than non-empty listsNote: the cmp
function will be called even if the lists have different lengths.
iter ~f [a1; ...; an]
applies function f
in turn to [a1; ...; an]
. It is equivalent to f a1; f a2; ...; f an
.
Same as iter
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
map ~f [a1; ...; an]
applies function f
to a1, ..., an
, and builds the list [f a1; ...; f an]
with the results returned by f
.
Same as map
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
filter_map ~f l
applies f
to every element of l
, filters out the None
elements and returns the list of the arguments of the Some
elements.
fold_left_map
is a combination of fold_left
and map
that threads an accumulator through calls to f
.
fold_left ~f ~init [b1; ...; bn]
is f (... (f (f init b1) b2) ...) bn
.
fold_right ~f [a1; ...; an] ~init
is f a1 (f a2 (... (f an init) ...))
. Not tail-recursive.
iter2 ~f [a1; ...; an] [b1; ...; bn]
calls in turn f a1 b1; ...; f an bn
.
map2 ~f [a1; ...; an] [b1; ...; bn]
is [f a1 b1; ...; f an bn]
.
fold_left2 ~f ~init [a1; ...; an] [b1; ...; bn]
is f (... (f (f init a1 b1) a2 b2) ...) an bn
.
fold_right2 ~f [a1; ...; an] [b1; ...; bn] ~init
is f a1 b1 (f a2 b2 (... (f an bn init) ...))
.
for_all ~f [a1; ...; an]
checks if all elements of the list satisfy the predicate f
. That is, it returns (f a1) && (f a2) && ... && (f an)
for a non-empty list and true
if the list is empty.
exists ~f [a1; ...; an]
checks if at least one element of the list satisfies the predicate f
. That is, it returns (f a1) || (f a2) || ... || (f an)
for a non-empty list and false
if the list is empty.
Same as for_all
, but for a two-argument predicate.
Same as exists
, but for a two-argument predicate.
mem a ~set
is true if and only if a
is equal to an element of set
.
find ~f l
returns the first element of the list l
that satisfies the predicate f
.
find ~f l
returns the first element of the list l
that satisfies the predicate f
. Returns None
if there is no value that satisfies f
in the list l
.
find_index ~f xs
returns Some i
, where i
is the index of the first element of the list xs
that satisfies f x
, if there is such an element.
It returns None
if there is no such element.
find_map ~f l
applies f
to the elements of l
in order, and returns the first result of the form Some v
, or None
if none exist.
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
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 is preserved.
find_all
is another name for filter
.
Same as filter
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
partition ~f l
returns a pair of lists (l1, l2)
, where l1
is the list of all the elements of l
that satisfy the predicate f
, and l2
is the list of all the elements of l
that do not satisfy f
. The order of the elements in the input list is preserved.
partition_map f l
returns a pair of lists (l1, l2)
such that, for each element x
of the input list l
:
f x
is Left y1
, then y1
is in l1
, andf x
is Right y2
, then y2
is in l2
.The output elements are included in l1
and l2
in the same relative order as the corresponding input elements in l
.
In particular, partition_map (fun x -> if f x then Left x else Right x) l
is equivalent to partition f l
.
assoc a l
returns the value associated with key a
in the list of pairs l
. That is, assoc a [ ...; (a,b); ...] = b
if (a,b)
is the leftmost binding of a
in list l
.
assoc_opt a l
returns the value associated with key a
in the list of pairs l
. That is, assoc_opt a [ ...; (a,b); ...] = Some b
if (a,b)
is the leftmost binding of a
in list l
. Returns None
if there is no value associated with a
in the list l
.
Same as assoc
, but simply return true
if a binding exists, and false
if no bindings exist for the given key.
remove_assoc a l
returns the list of pairs l
without the first pair with key a
, if any. Not tail-recursive.
Transform a list of pairs into a pair of lists: split [(a1,b1); ...; (an,bn)]
is ([a1; ...; an], [b1; ...; bn])
. Not tail-recursive.
Transform a pair of lists into a list of pairs: combine [a1; ...; an] [b1; ...; bn]
is [(a1,b1); ...; (an,bn)]
.
Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, Stdlib.compare
is a suitable comparison function. The resulting list is sorted in increasing order. sort
is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space.
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
, but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order).
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
or stable_sort
, whichever is faster on typical input.
Same as sort
, but also remove duplicates.
Merge two lists: Assuming that l1
and l2
are sorted according to the comparison function cmp
, merge ~cmp l1 l2
will return a sorted list containing all the elements of l1
and l2
. If several elements compare equal, the elements of l1
will be before the elements of l2
. Not tail-recursive (sum of the lengths of the arguments).
Same as mem
, but uses physical equality instead of structural equality to compare list elements.
Same as assoc
, but uses physical equality instead of structural equality to compare keys.
Same as assoc_opt
, but uses physical equality instead of structural equality to compare keys.
Same as mem_assoc
, but uses physical equality instead of structural equality to compare keys.
Same as remove_assoc
, but uses physical equality instead of structural equality to compare keys. Not tail-recursive.
StdLabels_alerting.String
include sig ... end
make n c
is a string of length n
with each index holding the character c
.
init n ~f
is a string of length n
with index i
holding the character f i
(called in increasing index order).
get s i
is the character at index i
in s
. This is the same as writing s.[i]
.
concat ~sep ss
concatenates the list of strings ss
, inserting the separator string sep
between each.
compare s0 s1
sorts s0
and s1
in lexicographical order. compare
behaves like Stdlib.compare
on strings but may be more efficient.
starts_with
~prefix s
is true
if and only if s
starts with prefix
.
ends_with
~suffix s
is true
if and only if s
ends with suffix
.
contains_from s start c
is true
if and only if c
appears in s
after position start
.
rcontains_from s stop c
is true
if and only if c
appears in s
before position stop+1
.
contains s c
is String.contains_from
s 0 c
.
sub s ~pos ~len
is a string of length len
, containing the substring of s
that starts at position pos
and has length len
.
split_on_char ~sep s
is the list of all (possibly empty) substrings of s
that are delimited by the character sep
.
The function's result is specified by the following invariants:
sep
as a separator returns a string equal to the input (concat (make 1 sep)
+ (split_on_char sep s) = s
).sep
character.map f s
is the string resulting from applying f
to all the characters of s
in increasing order.
mapi ~f s
is like map
but the index of the character is also passed to f
.
fold_left f x s
computes f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]
, where n
is the length of the string s
.
fold_right f s x
computes f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))
, where n
is the length of the string s
.
for_all p s
checks if all characters in s
satisfy the predicate p
.
exists p s
checks if at least one character of s
satisfies the predicate p
.
trim s
is s
without leading and trailing whitespace. Whitespace characters are: ' '
, '\x0C'
(form feed), '\n'
, '\r'
, and '\t'
.
escaped s
is s
with special characters represented by escape sequences, following the lexical conventions of OCaml.
All characters outside the US-ASCII printable range [0x20;0x7E] are escaped, as well as backslash (0x2F) and double-quote (0x22).
The function Scanf.unescaped
is a left inverse of escaped
, i.e. Scanf.unescaped (escaped s) = s
for any string s
(unless escaped s
fails).
uppercase_ascii s
is s
with all lowercase letters translated to uppercase, using the US-ASCII character set.
lowercase_ascii s
is s
with all uppercase letters translated to lowercase, using the US-ASCII character set.
capitalize_ascii s
is s
with the first character set to uppercase, using the US-ASCII character set.
uncapitalize_ascii s
is s
with the first character set to lowercase, using the US-ASCII character set.
iter ~f s
applies function f
in turn to all the characters of s
. It is equivalent to f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()
.
iteri
is like iter
, but the function is also given the corresponding character index.
index_from s i c
is the index of the first occurrence of c
in s
after position i
.
index_from_opt s i c
is the index of the first occurrence of c
in s
after position i
(if any).
rindex_from s i c
is the index of the last occurrence of c
in s
before position i+1
.
rindex_from_opt s i c
is the index of the last occurrence of c
in s
before position i+1
(if any).
index s c
is String.index_from
s 0 c
.
index_opt s c
is String.index_from_opt
s 0 c
.
rindex s c
is String.rindex_from
s (length s - 1) c
.
rindex_opt s c
is String.rindex_from_opt
s (length s - 1) c
.
val to_seq : t -> char Stdlib.Seq.t
to_seq s
is a sequence made of the string's characters in increasing order. In "unsafe-string"
mode, modifications of the string during iteration will be reflected in the sequence.
val to_seqi : t -> (int * char) Stdlib.Seq.t
to_seqi s
is like to_seq
but also tuples the corresponding index.
val of_seq : char Stdlib.Seq.t -> t
of_seq s
is a string made of the sequence's characters.
val get_utf_8_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_8_uchar b i
decodes an UTF-8 character at index i
in b
.
val is_valid_utf_8 : t -> bool
is_valid_utf_8 b
is true
if and only if b
contains valid UTF-8 data.
val get_utf_16be_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16be_uchar b i
decodes an UTF-16BE character at index i
in b
.
val is_valid_utf_16be : t -> bool
is_valid_utf_16be b
is true
if and only if b
contains valid UTF-16BE data.
val get_utf_16le_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16le_uchar b i
decodes an UTF-16LE character at index i
in b
.
val is_valid_utf_16le : t -> bool
is_valid_utf_16le b
is true
if and only if b
contains valid UTF-16LE data.
get_uint8 b i
is b
's unsigned 8-bit integer starting at character index i
.
get_int8 b i
is b
's signed 8-bit integer starting at character index i
.
get_uint16_ne b i
is b
's native-endian unsigned 16-bit integer starting at character index i
.
get_uint16_be b i
is b
's big-endian unsigned 16-bit integer starting at character index i
.
get_uint16_le b i
is b
's little-endian unsigned 16-bit integer starting at character index i
.
get_int16_ne b i
is b
's native-endian signed 16-bit integer starting at character index i
.
get_int16_be b i
is b
's big-endian signed 16-bit integer starting at character index i
.
get_int16_le b i
is b
's little-endian signed 16-bit integer starting at character index i
.
get_int32_ne b i
is b
's native-endian 32-bit integer starting at character index i
.
val hash : t -> int
An unseeded hash function for strings, with the same output value as Hashtbl.hash
. This function allows this module to be passed as argument to the functor Hashtbl.Make
.
val seeded_hash : int -> t -> int
A seeded hash function for strings, with the same output value as Hashtbl.seeded_hash
. This function allows this module to be passed as argument to the functor Hashtbl.MakeSeeded
.
get_int32_be b i
is b
's big-endian 32-bit integer starting at character index i
.
get_int32_le b i
is b
's little-endian 32-bit integer starting at character index i
.
get_int64_ne b i
is b
's native-endian 64-bit integer starting at character index i
.
get_int64_be b i
is b
's big-endian 64-bit integer starting at character index i
.
get_int64_le b i
is b
's little-endian 64-bit integer starting at character index i
.
Return a new string that contains the same bytes as the given byte sequence.
Return a new byte sequence that contains the same bytes as the given string.
Stdlib_alerts.StdLabels_alerting
module String : StringLabels_alerting
module List : ListLabels_alerting
Stdlib_alerting.Char
include sig ... end
Return a string representing the given character, with special characters escaped following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash, double-quote, and single-quote.
Convert the given character to its equivalent lowercase character, using the US-ASCII character set.
Convert the given character to its equivalent uppercase character, using the US-ASCII character set.
The 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 seeded_hash : int -> t -> int
A seeded hash function for characters, with the same output value as Hashtbl.seeded_hash
. This function allows this module to be passed as argument to the functor Hashtbl.MakeSeeded
.
val hash : t -> int
An unseeded hash function for characters, with the same output value as Hashtbl.hash
. This function allows this module to be passed as argument to the functor Hashtbl.Make
.
Stdlib_alerting.Digest
include sig ... end
The comparison function for 16-character digest, with the same specification as Stdlib.compare
and the implementation shared with String.compare
. Along with the type t
, this function compare
allows the module Digest
to be passed as argument to the functors Set.Make
and Map.Make
.
val string : string -> t
Return the digest of the given string.
val substring : string -> int -> int -> t
Digest.substring s ofs len
returns the digest of the substring of s
starting at index ofs
and containing len
characters.
val to_hex : t -> string
Return the printable hexadecimal representation of the given digest.
val from_hex : string -> t
Convert a hexadecimal representation back into the corresponding digest.
val bytes : bytes -> t
Return the digest of the given byte sequence.
val subbytes : bytes -> int -> int -> t
Digest.subbytes s ofs len
returns the digest of the subsequence of s
starting at index ofs
and containing len
bytes.
val channel : Stdlib.in_channel -> int -> t
If len
is nonnegative, Digest.channel ic len
reads len
characters from channel ic
and returns their digest, or raises End_of_file
if end-of-file is reached before len
characters are read. If len
is negative, Digest.channel ic len
reads all characters from ic
until end-of-file is reached and return their digest.
val file : string -> t
Return the digest of the file whose name is given.
val output : Stdlib.out_channel -> t -> unit
Write a digest on the given output channel.
val input : Stdlib.in_channel -> t
Read a digest from the given input channel.
Stdlib_alerting.Filename
include sig ... end
The conventional name for the parent of the current directory (e.g. ..
in Unix).
concat dir file
returns a file name that designates file file
in directory dir
.
Return true
if the file name is relative to the current directory, false
if it is absolute (i.e. in Unix, starts with /
).
Return true
if the file name is relative and does not start with an explicit reference to the current directory (./
or ../
in Unix), false
if it starts with an explicit reference to the root directory or the current directory.
check_suffix name suff
returns true
if the filename name
ends with the suffix suff
.
Under Windows ports (including Cygwin), comparison is case-insensitive, relying on String.lowercase_ascii
. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows.
chop_suffix name suff
removes the suffix suff
from the filename name
.
chop_suffix_opt ~suffix filename
removes the suffix from the filename
if possible, or returns None
if the filename does not end with the suffix.
Under Windows ports (including Cygwin), comparison is case-insensitive, relying on String.lowercase_ascii
. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows.
extension name
is the shortest suffix ext
of name0
where:
name0
is the longest suffix of name
that does not contain a directory separator;ext
starts with a period;ext
is preceded by at least one non-period character in name0
.If such a suffix does not exist, extension name
is the empty string.
Return the given file name without its extension, as defined in Filename.extension
. If the extension is empty, the function returns the given file name.
The following invariant holds for any file name s
:
remove_extension s ^ extension s = s
Same as Filename.remove_extension
, but raise Invalid_argument
if the given name has an empty extension.
Split a file name into directory name / base file name. If name
is a valid file name, then concat (dirname name) (basename name)
returns a file name which is equivalent to name
. Moreover, after setting the current directory to dirname name
(with Sys.chdir
), references to basename name
(which is a relative file name) designate the same file as name
before the call to Sys.chdir
.
This function conforms to the specification of POSIX.1-2008 for the basename
utility.
See Filename.basename
. This function conforms to the specification of POSIX.1-2008 for the dirname
utility.
null
is "/dev/null"
on POSIX and "NUL"
on Windows. It represents a file on the OS that discards all writes and returns end of file on reads.
Return a quoted version of a file name, suitable for use as one argument in a command line, escaping all meta-characters. Warning: under Windows, the output is only suitable for use with programs that follow the standard Windows quoting conventions.
val quote_command :
+ string ->
+ ?stdin:string ->
+ ?stdout:string ->
+ ?stderr:string ->
+ string list ->
+ string
quote_command cmd args
returns a quoted command line, suitable for use as an argument to Sys.command
, Unix.system
, and the Unix.open_process
functions.
The string cmd
is the command to call. The list args
is the list of arguments to pass to this command. It can be empty.
The optional arguments ?stdin
and ?stdout
and ?stderr
are file names used to redirect the standard input, the standard output, or the standard error of the command. If ~stdin:f
is given, a redirection < f
is performed and the standard input of the command reads from file f
. If ~stdout:f
is given, a redirection > f
is performed and the standard output of the command is written to file f
. If ~stderr:f
is given, a redirection 2> f
is performed and the standard error of the command is written to file f
. If both ~stdout:f
and ~stderr:f
are given, with the exact same file name f
, a 2>&1
redirection is performed so that the standard output and the standard error of the command are interleaved and redirected to the same file f
.
Under Unix and Cygwin, the command, the arguments, and the redirections if any are quoted using Filename.quote
, then concatenated. Under Win32, additional quoting is performed as required by the cmd.exe
shell that is called by Sys.command
.
temp_file prefix suffix
returns the name of a fresh temporary file in the temporary directory. The base name of the temporary file is formed by concatenating prefix
, then a suitably chosen integer number, then suffix
. The optional argument temp_dir
indicates the temporary directory to use, defaulting to the current result of Filename.get_temp_dir_name
. The temporary file is created empty, with permissions 0o600
(readable and writable only by the file owner). The file is guaranteed to be different from any other file that existed when temp_file
was called.
val open_temp_file :
+ ?mode:Stdlib.open_flag list ->
+ ?perms:int ->
+ ?temp_dir:string ->
+ string ->
+ string ->
+ string * Stdlib.out_channel
Same as Filename.temp_file
, but returns both the name of a fresh temporary file, and an output channel opened (atomically) on this file. This function is more secure than temp_file
: there is no risk that the temporary file will be modified (e.g. replaced by a symbolic link) before the program opens it. The optional argument mode
is a list of additional flags to control the opening of the file. It can contain one or several of Open_append
, Open_binary
, and Open_text
. The default is [Open_text]
(open in text mode). The file is created with permissions perms
(defaults to readable and writable only by the file owner, 0o600
).
temp_dir prefix suffix
creates and returns the name of a fresh temporary directory with permissions perms
(defaults to 0o700) inside temp_dir
. The base name of the temporary directory is formed by concatenating prefix
, then a suitably chosen integer number, then suffix
. The optional argument temp_dir
indicates the temporary directory to use, defaulting to the current result of Filename.get_temp_dir_name
. The temporary directory is created empty, with permissions 0o700
(readable, writable, and searchable only by the file owner). The directory is guaranteed to be different from any other directory that existed when temp_dir
was called.
If temp_dir does not exist, this function does not create it. Instead, it raises Sys_error.
The name of the temporary directory: Under Unix, the value of the TMPDIR
environment variable, or "/tmp" if the variable is not set. Under Windows, the value of the TEMP
environment variable, or "." if the variable is not set. The temporary directory can be changed with Filename.set_temp_dir_name
.
Change the temporary directory returned by Filename.get_temp_dir_name
and used by Filename.temp_file
and Filename.open_temp_file
. The temporary directory is a domain-local value which is inherited by child domains.
Float.Array
Float arrays with packed representation.
val length : t -> int
Return the length (number of elements) of the given floatarray.
val get : t -> int -> float
get a n
returns the element number n
of floatarray a
.
val set : t -> int -> float -> unit
set a n x
modifies floatarray a
in place, replacing element number n
with x
.
val make : int -> float -> t
make n x
returns a fresh floatarray of length n
, initialized with x
.
val create : int -> t
create n
returns a fresh floatarray of length n
, with uninitialized data.
val init : int -> (int -> float) -> t
init n f
returns a fresh floatarray of length n
, with element number i
initialized to the result of f i
. In other terms, init n f
tabulates the results of f
applied to the integers 0
to n-1
.
append v1 v2
returns a fresh floatarray containing the concatenation of the floatarrays v1
and v2
.
sub a pos len
returns a fresh floatarray of length len
, containing the elements number pos
to pos + len - 1
of floatarray a
.
copy a
returns a copy of a
, that is, a fresh floatarray containing the same elements as a
.
val fill : t -> int -> int -> float -> unit
fill a pos len x
modifies the floatarray a
in place, storing x
in elements number pos
to pos + len - 1
.
blit src src_pos dst dst_pos len
copies len
elements from floatarray src
, starting at element number src_pos
, to floatarray dst
, starting at element number dst_pos
. It works correctly even if src
and dst
are the same floatarray, and the source and destination chunks overlap.
val to_list : t -> float list
to_list a
returns the list of all the elements of a
.
val of_list : float list -> t
of_list l
returns a fresh floatarray containing the elements of l
.
val iter : (float -> unit) -> t -> unit
iter f a
applies function f
in turn to all the elements of a
. It is equivalent to f a.(0); f a.(1); ...; f a.(length a - 1); ()
.
val iteri : (int -> float -> unit) -> t -> unit
Same as iter
, but the function is applied with the index of the element as first argument, and the element itself as second argument.
map f a
applies function f
to all the elements of a
, and builds a floatarray with the results returned by f
.
val map_inplace : (float -> float) -> t -> unit
map_inplace f a
applies function f
to all elements of a
, and updates their values in place.
Same as map
, but the function is applied to the index of the element as first argument, and the element itself as second argument.
val mapi_inplace : (int -> float -> float) -> t -> unit
Same as map_inplace
, but the function is applied to the index of the element as first argument, and the element itself as second argument.
val fold_left : ('acc -> float -> 'acc) -> 'acc -> t -> 'acc
fold_left f x init
computes f (... (f (f x init.(0)) init.(1)) ...) init.(n-1)
, where n
is the length of the floatarray init
.
val fold_right : (float -> 'acc -> 'acc) -> t -> 'acc -> 'acc
fold_right f a init
computes f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))
, where n
is the length of the floatarray a
.
Array.iter2 f a b
applies function f
to all the elements of a
and b
.
map2 f a b
applies function f
to all the elements of a
and b
, and builds a floatarray with the results returned by f
: [| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]
.
val for_all : (float -> bool) -> t -> bool
for_all f [|a1; ...; an|]
checks if all elements of the floatarray satisfy the predicate f
. That is, it returns (f a1) && (f a2) && ... && (f an)
.
val exists : (float -> bool) -> t -> bool
exists f [|a1; ...; an|]
checks if at least one element of the floatarray satisfies the predicate f
. That is, it returns (f a1) || (f a2) || ... || (f an)
.
val mem : float -> t -> bool
mem a set
is true if and only if there is an element of set
that is structurally equal to a
, i.e. there is an x
in set
such that compare a x = 0
.
val mem_ieee : float -> t -> bool
Same as mem
, but uses IEEE equality instead of structural equality.
val find_opt : (float -> bool) -> t -> float option
val find_index : (float -> bool) -> t -> int option
find_index f a
returns Some i
, where i
is the index of the first element of the array a
that satisfies f x
, if there is such an element.
It returns None
if there is no such element.
val find_map : (float -> 'a option) -> t -> 'a option
val find_mapi : (int -> float -> 'a option) -> t -> 'a option
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
val sort : (float -> float -> int) -> t -> unit
Sort a floatarray in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, Stdlib.compare
is a suitable comparison function. After calling sort
, the array is sorted in place in increasing order. sort
is guaranteed to run in constant heap space and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant stack space.
Specification of the comparison function: Let a
be the floatarray and cmp
the comparison function. The following must be true for all x
, y
, z
in a
:
cmp x y
> 0 if and only if cmp y x
< 0cmp x y
>= 0 and cmp y z
>= 0 then cmp x z
>= 0When sort
returns, a
contains the same elements as before, reordered in such a way that for all i and j valid indices of a
:
cmp a.(i) a.(j)
>= 0 if and only if i >= jval stable_sort : (float -> float -> int) -> t -> unit
Same as sort
, but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space.
The current implementation uses Merge Sort. It uses a temporary floatarray of length n/2
, where n
is the length of the floatarray. It is usually faster than the current implementation of sort
.
val fast_sort : (float -> float -> int) -> t -> unit
Same as sort
or stable_sort
, whichever is faster on typical input.
val to_seq : t -> float Stdlib.Seq.t
Iterate on the floatarray, in increasing order. Modifications of the floatarray during iteration will be reflected in the sequence.
val to_seqi : t -> (int * float) Stdlib.Seq.t
Iterate on the floatarray, in increasing order, yielding indices along elements. Modifications of the floatarray during iteration will be reflected in the sequence.
val of_seq : float Stdlib.Seq.t -> t
Create an array from the generator.
val map_to_array : (float -> 'a) -> t -> 'a array
map_to_array f a
applies function f
to all the elements of a
, and builds an array with the results returned by f
: [| f a.(0); f a.(1); ...; f a.(length a - 1) |]
.
val map_from_array : ('a -> float) -> 'a array -> t
map_from_array f a
applies function f
to all the elements of a
, and builds a floatarray with the results returned by f
.
Care must be taken when concurrently accessing float arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results.
Every float array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays.
For example, consider the following program:
let size = 100_000_000
+let a = Float.Array.make size 1.
+let update a f () =
+ Float.Array.iteri (fun i x -> Float.Array.set a i (f x)) a
+let d1 = Domain.spawn (update a (fun x -> x +. 1.))
+let d2 = Domain.spawn (update a (fun x -> 2. *. x +. 1.))
+let () = Domain.join d1; Domain.join d2
After executing this code, each field of the float array a
is either 2.
, 3.
, 4.
or 5.
. If atomicity is required, then the user must implement their own synchronization (for example, using Mutex.t
).
If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains.
A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains.
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements.
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location with a few exceptions.
Float arrays have two supplementary caveats in the presence of data races.
First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution.
For instance, at the end of
let zeros = Float.Array.make size 0.
+let max_floats = Float.Array.make size Float.max_float
+let res = Float.Array.copy zeros
+let d1 = Domain.spawn (fun () -> Float.Array.blit zeros 0 res 0 size)
+let d2 = Domain.spawn (fun () -> Float.Array.blit max_floats 0 res 0 size)
+let () = Domain.join d1; Domain.join d2
the res
float array might contain values that are neither 0.
nor max_float
.
Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation.
Float.ArrayLabels
Float arrays with packed representation (labeled functions).
val length : t -> int
Return the length (number of elements) of the given floatarray.
val get : t -> int -> float
get a n
returns the element number n
of floatarray a
.
val set : t -> int -> float -> unit
set a n x
modifies floatarray a
in place, replacing element number n
with x
.
val make : int -> float -> t
make n x
returns a fresh floatarray of length n
, initialized with x
.
val create : int -> t
create n
returns a fresh floatarray of length n
, with uninitialized data.
val init : int -> f:(int -> float) -> t
init n ~f
returns a fresh floatarray of length n
, with element number i
initialized to the result of f i
. In other terms, init n ~f
tabulates the results of f
applied to the integers 0
to n-1
.
append v1 v2
returns a fresh floatarray containing the concatenation of the floatarrays v1
and v2
.
sub a ~pos ~len
returns a fresh floatarray of length len
, containing the elements number pos
to pos + len - 1
of floatarray a
.
copy a
returns a copy of a
, that is, a fresh floatarray containing the same elements as a
.
val fill : t -> pos:int -> len:int -> float -> unit
fill a ~pos ~len x
modifies the floatarray a
in place, storing x
in elements number pos
to pos + len - 1
.
blit ~src ~src_pos ~dst ~dst_pos ~len
copies len
elements from floatarray src
, starting at element number src_pos
, to floatarray dst
, starting at element number dst_pos
. It works correctly even if src
and dst
are the same floatarray, and the source and destination chunks overlap.
val to_list : t -> float list
to_list a
returns the list of all the elements of a
.
val of_list : float list -> t
of_list l
returns a fresh floatarray containing the elements of l
.
val iter : f:(float -> unit) -> t -> unit
iter ~f a
applies function f
in turn to all the elements of a
. It is equivalent to f a.(0); f a.(1); ...; f a.(length a - 1); ()
.
val iteri : f:(int -> float -> unit) -> t -> unit
Same as iter
, but the function is applied with the index of the element as first argument, and the element itself as second argument.
map ~f a
applies function f
to all the elements of a
, and builds a floatarray with the results returned by f
.
val map_inplace : f:(float -> float) -> t -> unit
map_inplace f a
applies function f
to all elements of a
, and updates their values in place.
Same as map
, but the function is applied to the index of the element as first argument, and the element itself as second argument.
val mapi_inplace : f:(int -> float -> float) -> t -> unit
Same as map_inplace
, but the function is applied to the index of the element as first argument, and the element itself as second argument.
val fold_left : f:('acc -> float -> 'acc) -> init:'acc -> t -> 'acc
fold_left ~f x ~init
computes f (... (f (f x init.(0)) init.(1)) ...) init.(n-1)
, where n
is the length of the floatarray init
.
val fold_right : f:(float -> 'acc -> 'acc) -> t -> init:'acc -> 'acc
fold_right f a init
computes f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))
, where n
is the length of the floatarray a
.
Array.iter2 ~f a b
applies function f
to all the elements of a
and b
.
map2 ~f a b
applies function f
to all the elements of a
and b
, and builds a floatarray with the results returned by f
: [| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]
.
val for_all : f:(float -> bool) -> t -> bool
for_all ~f [|a1; ...; an|]
checks if all elements of the floatarray satisfy the predicate f
. That is, it returns (f a1) && (f a2) && ... && (f an)
.
val exists : f:(float -> bool) -> t -> bool
exists f [|a1; ...; an|]
checks if at least one element of the floatarray satisfies the predicate f
. That is, it returns (f a1) || (f a2) || ... || (f an)
.
val mem : float -> set:t -> bool
mem a ~set
is true if and only if there is an element of set
that is structurally equal to a
, i.e. there is an x
in set
such that compare a x = 0
.
val mem_ieee : float -> set:t -> bool
Same as mem
, but uses IEEE equality instead of structural equality.
val find_opt : f:(float -> bool) -> t -> float option
val find_index : f:(float -> bool) -> t -> int option
find_index ~f a
returns Some i
, where i
is the index of the first element of the array a
that satisfies f x
, if there is such an element.
It returns None
if there is no such element.
val find_map : f:(float -> 'a option) -> t -> 'a option
val find_mapi : f:(int -> float -> 'a option) -> t -> 'a option
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
val sort : cmp:(float -> float -> int) -> t -> unit
Sort a floatarray in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, Stdlib.compare
is a suitable comparison function. After calling sort
, the array is sorted in place in increasing order. sort
is guaranteed to run in constant heap space and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant stack space.
Specification of the comparison function: Let a
be the floatarray and cmp
the comparison function. The following must be true for all x
, y
, z
in a
:
cmp x y
> 0 if and only if cmp y x
< 0cmp x y
>= 0 and cmp y z
>= 0 then cmp x z
>= 0When sort
returns, a
contains the same elements as before, reordered in such a way that for all i and j valid indices of a
:
cmp a.(i) a.(j)
>= 0 if and only if i >= jval stable_sort : cmp:(float -> float -> int) -> t -> unit
Same as sort
, but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space.
The current implementation uses Merge Sort. It uses a temporary floatarray of length n/2
, where n
is the length of the floatarray. It is usually faster than the current implementation of sort
.
val fast_sort : cmp:(float -> float -> int) -> t -> unit
Same as sort
or stable_sort
, whichever is faster on typical input.
val to_seq : t -> float Stdlib.Seq.t
Iterate on the floatarray, in increasing order. Modifications of the floatarray during iteration will be reflected in the sequence.
val to_seqi : t -> (int * float) Stdlib.Seq.t
Iterate on the floatarray, in increasing order, yielding indices along elements. Modifications of the floatarray during iteration will be reflected in the sequence.
val of_seq : float Stdlib.Seq.t -> t
Create an array from the generator.
val map_to_array : f:(float -> 'a) -> t -> 'a array
map_to_array ~f a
applies function f
to all the elements of a
, and builds an array with the results returned by f
: [| f a.(0); f a.(1); ...; f a.(length a - 1) |]
.
val map_from_array : f:('a -> float) -> 'a array -> t
map_from_array ~f a
applies function f
to all the elements of a
, and builds a floatarray with the results returned by f
.
Care must be taken when concurrently accessing float arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results.
Every float array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays.
For example, consider the following program:
let size = 100_000_000
+let a = Float.ArrayLabels.make size 1.
+let update a f () =
+ Float.ArrayLabels.iteri ~f:(fun i x -> Float.Array.set a i (f x)) a
+let d1 = Domain.spawn (update a (fun x -> x +. 1.))
+let d2 = Domain.spawn (update a (fun x -> 2. *. x +. 1.))
+let () = Domain.join d1; Domain.join d2
After executing this code, each field of the float array a
is either 2.
, 3.
, 4.
or 5.
. If atomicity is required, then the user must implement their own synchronization (for example, using Mutex.t
).
If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains.
A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains.
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements.
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location with a few exceptions.
Float arrays have two supplementary caveats in the presence of data races.
First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution.
For instance, at the end of
let zeros = Float.Array.make size 0.
+let max_floats = Float.Array.make size Float.max_float
+let res = Float.Array.copy zeros
+let d1 = Domain.spawn (fun () -> Float.Array.blit zeros 0 res 0 size)
+let d2 = Domain.spawn (fun () -> Float.Array.blit max_floats 0 res 0 size)
+let () = Domain.join d1; Domain.join d2
the res
float array might contain values that are neither 0.
nor max_float
.
Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation.
Stdlib_alerting.Float
include sig ... end
fma x y z
returns x * y + z
, with a best effort for computing this expression with a single rounding, using either hardware instructions (providing full IEEE compliance) or a software emulation.
On 64-bit Cygwin, 64-bit mingw-w64 and MSVC 2017 and earlier, this function may be emulated owing to known bugs on limitations on these platforms. Note: since software emulation of the fma is costly, make sure that you are using hardware fma support if performance matters.
rem a b
returns the remainder of a
with respect to b
. The returned value is a -. n *. b
, where n
is the quotient a /. b
rounded towards zero to an integer.
succ x
returns the floating point number right after x
i.e., the smallest floating-point number greater than x
. See also next_after
.
pred x
returns the floating-point number right before x
i.e., the greatest floating-point number smaller than x
. See also next_after
.
A special floating-point value denoting the result of an undefined operation such as 0.0 /. 0.0
. Stands for 'not a number'. Any floating-point operation with nan
as argument returns nan
as result, unless otherwise specified in IEEE 754 standard. As for floating-point comparisons, =
, <
, <=
, >
and >=
return false
and <>
returns true
if one or both of their arguments is nan
.
nan
is quiet_nan
since 5.1; it was a signaling NaN before.
Signaling NaN. The corresponding signals do not raise OCaml exception, but the value can be useful for interoperability with C libraries.
The difference between 1.0
and the smallest exactly representable floating-point number greater than 1.0
.
is_finite x
is true
if and only if x
is finite i.e., not infinite and not nan
.
is_infinite x
is true
if and only if x
is infinity
or neg_infinity
.
is_nan x
is true
if and only if x
is not a number (see nan
).
Truncate the given floating-point number to an integer. The result is unspecified if the argument is nan
or falls outside the range of representable integers.
Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by 0x
or 0X
). The format of decimal floating-point numbers is [-] dd.ddd (e|E) [+|-] dd
, where d
stands for a decimal digit. The format of hexadecimal floating-point numbers is [-] 0(x|X) hh.hhh (p|P) [+|-] dd
, where h
stands for an hexadecimal digit and d
for a decimal digit. In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional. The _
(underscore) character can appear anywhere in the string and is ignored. Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon.
Return a string representation of a floating-point number.
This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see Printf
.
This function is an alias for Stdlib.string_of_float
.
The five classes of floating-point numbers, as determined by the classify_float
function.
val classify_float : float -> fpclass
Return the class of the given floating-point number: normal, subnormal, zero, infinite, or not a number.
expm1 x
computes exp x -. 1.0
, giving numerically-accurate results even if x
is close to 0.0
.
log1p x
computes log(1.0 +. x)
(natural logarithm), giving numerically-accurate results even if x
is close to 0.0
.
Arc cosine. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and is between 0.0
and pi
.
Arc sine. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and is between -pi/2
and pi/2
.
atan2 y x
returns the arc tangent of y /. x
. The signs of x
and y
are used to determine the quadrant of the result. Result is in radians and is between -pi
and pi
.
hypot x y
returns sqrt(x *. x +. y *. y)
, that is, the length of the hypotenuse of a right-angled triangle with sides of length x
and y
, or, equivalently, the distance of the point (x,y)
to origin. If one of x
or y
is infinite, returns infinity
even if the other is nan
.
Hyperbolic arc cosine. The argument must fall within the range [1.0, inf]
. Result is in radians and is between 0.0
and inf
.
Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians.
Hyperbolic arc tangent. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and ranges over the entire real line.
Error function. The argument ranges over the entire real line. The result is always within [-1.0, 1.0]
.
Complementary error function (erfc x = 1 - erf x
). The argument ranges over the entire real line. The result is always within [-1.0, 1.0]
.
trunc x
rounds x
to the nearest integer whose absolute value is less than or equal to x
.
round x
rounds x
to the nearest integer with ties (fractional values of 0.5) rounded away from zero, regardless of the current rounding direction. If x
is an integer, +0.
, -0.
, nan
, or infinite, x
itself is returned.
On 64-bit mingw-w64, this function may be emulated owing to a bug in the C runtime library (CRT) on this platform.
Round above to an integer value. ceil f
returns the least integer value greater than or equal to f
. The result is returned as a float.
Round below to an integer value. floor f
returns the greatest integer value less than or equal to f
. The result is returned as a float.
next_after x y
returns the next representable floating-point value following x
in the direction of y
. More precisely, if y
is greater (resp. less) than x
, it returns the smallest (resp. largest) representable number greater (resp. less) than x
. If x
equals y
, the function returns y
. If x
or y
is nan
, a nan
is returned. Note that next_after max_float infinity = infinity
and that next_after 0. infinity
is the smallest denormalized positive number. If x
is the smallest denormalized positive number, next_after x 0. = 0.
copy_sign x y
returns a float whose absolute value is that of x
and whose sign is that of y
. If x
is nan
, returns nan
. If y
is nan
, returns either x
or -. x
, but it is not specified which.
sign_bit x
is true
if and only if the sign bit of x
is set. For example sign_bit 1.
and signbit 0.
are false
while sign_bit (-1.)
and sign_bit (-0.)
are true
.
frexp f
returns the pair of the significant and the exponent of f
. When f
is zero, the significant x
and the exponent n
of f
are equal to zero. When f
is non-zero, they are defined by f = x *. 2 ** n
and 0.5 <= x < 1.0
.
compare x y
returns 0
if x
is equal to y
, a negative integer if x
is less than y
, and a positive integer if x
is greater than y
. compare
treats nan
as equal to itself and less than any other float value. This treatment of nan
ensures that compare
defines a total ordering relation.
min x y
returns the minimum of x
and y
. It returns nan
when x
or y
is nan
. Moreover min (-0.) (+0.) = -0.
max x y
returns the maximum of x
and y
. It returns nan
when x
or y
is nan
. Moreover max (-0.) (+0.) = +0.
min_max x y
is (min x y, max x y)
, just more efficient.
min_num x y
returns the minimum of x
and y
treating nan
as missing values. If both x
and y
are nan
, nan
is returned. Moreover min_num (-0.) (+0.) = -0.
max_num x y
returns the maximum of x
and y
treating nan
as missing values. If both x
and y
are nan
nan
is returned. Moreover max_num (-0.) (+0.) = +0.
min_max_num x y
is (min_num x y, max_num x y)
, just more efficient. Note that in particular min_max_num x nan = (x, x)
and min_max_num nan y = (y, y)
.
val seeded_hash : int -> t -> int
A seeded hash function for floats, with the same output value as Hashtbl.seeded_hash
. This function allows this module to be passed as argument to the functor Hashtbl.MakeSeeded
.
val hash : t -> int
An unseeded hash function for floats, with the same output value as Hashtbl.hash
. This function allows this module to be passed as argument to the functor Hashtbl.Make
.
module Array : sig ... end
Float arrays with packed representation.
module ArrayLabels : sig ... end
Float arrays with packed representation (labeled functions).
Make.H
val hash : t -> int
A hashing function on keys. It must be such that if two keys are equal according to equal
, then they have identical hash values as computed by hash
. Examples: suitable (equal
, hash
) pairs for arbitrary key types include
Hashtbl.Make
Functor building an implementation of the hashtable structure. The functor Hashtbl.Make
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. Since the hash function is not seeded, the create
operation of the result structure always returns non-randomized hash tables.
module H : HashedType
type key = H.t
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
MakeSeeded.H
val seeded_hash : int -> t -> int
A seeded hashing function on keys. The first argument is the seed. It must be the case that if equal x y
is true, then seeded_hash seed x = seeded_hash seed y
for any value of seed
. A suitable choice for seeded_hash
is the function Hashtbl.seeded_hash
below.
Hashtbl.MakeSeeded
Functor building an implementation of the hashtable structure. The functor Hashtbl.MakeSeeded
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. The create
operation of the result structure supports the ~random
optional parameter and returns randomized hash tables if ~random:true
is passed or if randomization is globally on (see Hashtbl.randomize
).
module H : SeededHashedType
type key = H.t
val create : ?random:bool -> int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
Stdlib_alerting.Hashtbl
include sig ... end
Hashtbl.hash x
associates a nonnegative integer to any value of any type. It is guaranteed that if x = y
or Stdlib.compare x y = 0
, then hash x = hash y
. Moreover, hash
always terminates, even on cyclic structures.
A variant of hash
that is further parameterized by an integer seed.
Hashtbl.hash_param meaningful total x
computes a hash value for x
, with the same properties as for hash
. The two extra integer parameters meaningful
and total
give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure x
, stopping after meaningful
meaningful nodes were encountered, or total
nodes (meaningful or not) were encountered. If total
as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of meaningful
and total
means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters meaningful
and total
govern the tradeoff between accuracy and speed. As default choices, hash
and seeded_hash
take meaningful = 10
and total = 100
.
A variant of hash_param
that is further parameterized by an integer seed. Usage: Hashtbl.seeded_hash_param meaningful total seed x
.
val create : ?random:bool -> int -> ('a, 'b) t
Hashtbl.create n
creates a new, empty hash table, with initial size n
. For best results, n
should be on the order of the expected number of elements that will be in the table. The table grows as needed, so n
is just an initial guess.
The optional ~random
parameter (a boolean) controls whether the internal organization of the hash table is randomized at each execution of Hashtbl.create
or deterministic over all executions.
A hash table that is created with ~random
set to false
uses a fixed hash function (hash
) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down.
A hash table that is created with ~random
set to true
uses the seeded hash function seeded_hash
with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among 2^{30}
different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using fold
or iter
is no longer deterministic: elements are enumerated in different orders at different runs of the program.
If no ~random
parameter is given, hash tables are created in non-random mode by default. This default can be changed either programmatically by calling randomize
or by setting the R
flag in the OCAMLRUNPARAM
environment variable.
val clear : ('a, 'b) t -> unit
Empty a hash table. Use reset
instead of clear
to shrink the size of the bucket table to its initial size.
val reset : ('a, 'b) t -> unit
Empty a hash table and shrink the size of the bucket table to its initial size.
val add : ('a, 'b) t -> 'a -> 'b -> unit
Hashtbl.add tbl key data
adds a binding of key
to data
in table tbl
.
Warning: Previous bindings for key
are not removed, but simply hidden. That is, after performing remove
tbl key
, the previous binding for key
, if any, is restored. (Same behavior as with association lists.)
If you desire the classic behavior of replacing elements, see replace
.
val find : ('a, 'b) t -> 'a -> 'b
Hashtbl.find tbl x
returns the current binding of x
in tbl
, or raises Not_found
if no such binding exists.
val find_opt : ('a, 'b) t -> 'a -> 'b option
Hashtbl.find_opt tbl x
returns the current binding of x
in tbl
, or None
if no such binding exists.
val find_all : ('a, 'b) t -> 'a -> 'b list
Hashtbl.find_all tbl x
returns the list of all data associated with x
in tbl
. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table.
val mem : ('a, 'b) t -> 'a -> bool
Hashtbl.mem tbl x
checks if x
is bound in tbl
.
val remove : ('a, 'b) t -> 'a -> unit
Hashtbl.remove tbl x
removes the current binding of x
in tbl
, restoring the previous binding if it exists. It does nothing if x
is not bound in tbl
.
val replace : ('a, 'b) t -> 'a -> 'b -> unit
val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit
Hashtbl.iter f tbl
applies f
to all bindings in table tbl
. f
receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to f
.
The order in which the bindings are passed to f
is unspecified. However, if the table contains several bindings for the same key, they are passed to f
in reverse order of introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.
The behavior is not specified if the hash table is modified by f
during the iteration.
val filter_map_inplace : ('a -> 'b -> 'b option) -> ('a, 'b) t -> unit
Hashtbl.filter_map_inplace f tbl
applies f
to all bindings in table tbl
and update each binding depending on the result of f
. If f
returns None
, the binding is discarded. If it returns Some new_val
, the binding is update to associate the key to new_val
.
Other comments for iter
apply as well.
val fold : ('a -> 'b -> 'acc -> 'acc) -> ('a, 'b) t -> 'acc -> 'acc
Hashtbl.fold f tbl init
computes (f kN dN ... (f k1 d1 init)...)
, where k1 ... kN
are the keys of all bindings in tbl
, and d1 ... dN
are the associated values. Each binding is presented exactly once to f
.
The order in which the bindings are passed to f
is unspecified. However, if the table contains several bindings for the same key, they are passed to f
in reverse order of introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.
The behavior is not specified if the hash table is modified by f
during the iteration.
val length : ('a, 'b) t -> int
Hashtbl.length tbl
returns the number of bindings in tbl
. It takes constant time. Multiple bindings are counted once each, so Hashtbl.length
gives the number of times Hashtbl.iter
calls its first argument.
After a call to Hashtbl.randomize()
, hash tables are created in randomized mode by default: create
returns randomized hash tables, unless the ~random:false
optional parameter is given. The same effect can be achieved by setting the R
parameter in the OCAMLRUNPARAM
environment variable.
It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in create
call Hashtbl.randomize()
at initialization time before any domains are created.
Note that once Hashtbl.randomize()
was called, there is no way to revert to the non-randomized default behavior of create
. This is intentional. Non-randomized hash tables can still be created using Hashtbl.create ~random:false
.
Return true
if the tables are currently created in randomized mode by default, false
otherwise.
Return a copy of the given hashtable. Unlike copy
, rebuild
h
re-hashes all the (key, value) entries of the original table h
. The returned hash table is randomized if h
was randomized, or the optional random
parameter is true, or if the default is to create randomized hash tables; see create
for more information.
rebuild
can safely be used to import a hash table built by an old version of the Hashtbl
module, then marshaled to persistent storage. After unmarshaling, apply rebuild
to produce a hash table for the current version of the Hashtbl
module.
type statistics = {
num_bindings : int;
num_buckets : int;
Number of buckets in the table.
*)max_bucket_length : int;
Maximal number of bindings per bucket.
*)bucket_histogram : int array;
Histogram of bucket sizes. This array histo
has length max_bucket_length + 1
. The value of histo.(i)
is the number of buckets whose size is i
.
}
val stats : ('a, 'b) t -> statistics
Hashtbl.stats tbl
returns statistics about the table tbl
: number of buckets, size of the biggest bucket, distribution of buckets by size.
val to_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t
Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first.
The behavior is not specified if the hash table is modified during the iteration.
val to_seq_keys : ('a, _) t -> 'a Stdlib.Seq.t
Same as Seq.map fst (to_seq m)
val to_seq_values : (_, 'b) t -> 'b Stdlib.Seq.t
Same as Seq.map snd (to_seq m)
val add_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t -> unit
Add the given bindings to the table, using add
val replace_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t -> unit
Add the given bindings to the table, using replace
val of_seq : ('a * 'b) Stdlib.Seq.t -> ('a, 'b) t
Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using replace_seq
, which means that if two pairs have the same key, only the latest one will appear in the table.
module type HashedType = sig ... end
The input signature of the functor Make
.
Functor building an implementation of the hashtable structure. The functor Hashtbl.Make
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. Since the hash function is not seeded, the create
operation of the result structure always returns non-randomized hash tables.
module type SeededHashedType = sig ... end
The input signature of the functor MakeSeeded
.
module type SeededS = sig ... end
The output signature of the functor MakeSeeded
.
module MakeSeeded (H : SeededHashedType) : SeededS with type key = H.t
Functor building an implementation of the hashtable structure. The functor Hashtbl.MakeSeeded
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. The create
operation of the result structure supports the ~random
optional parameter and returns randomized hash tables if ~random:true
is passed or if randomization is globally on (see Hashtbl.randomize
).
Hashtbl.HashedType
The input signature of the functor Make
.
val hash : t -> int
A hashing function on keys. It must be such that if two keys are equal according to equal
, then they have identical hash values as computed by hash
. Examples: suitable (equal
, hash
) pairs for arbitrary key types include
Hashtbl.S
The output signature of the functor Make
.
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
Hashtbl.SeededHashedType
The input signature of the functor MakeSeeded
.
val seeded_hash : int -> t -> int
A seeded hashing function on keys. The first argument is the seed. It must be the case that if equal x y
is true, then seeded_hash seed x = seeded_hash seed y
for any value of seed
. A suitable choice for seeded_hash
is the function Hashtbl.seeded_hash
below.
Hashtbl.SeededS
The output signature of the functor MakeSeeded
.
val create : ?random:bool -> int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
Stdlib_alerting.LargeFile
Operations on large files. This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type int64
) instead of regular integers (type int
), these alternate functions allow operating on files whose sizes are greater than max_int
.
val seek_out : out_channel -> int64 -> unit
val pos_out : out_channel -> int64
val out_channel_length : out_channel -> int64
val seek_in : in_channel -> int64 -> unit
val pos_in : in_channel -> int64
val in_channel_length : in_channel -> int64
Stdlib_alerting.List
include sig ... end
Compare the lengths of two lists. compare_lengths l1 l2
is equivalent to compare (length l1) (length l2)
, except that the computation stops after reaching the end of the shortest list.
Compare the length of a list to an integer. compare_length_with l len
is equivalent to compare (length l) len
, except that the computation stops after at most len
iterations on the list.
is_empty l
is true if and only if l
has no elements. It is equivalent to compare_length_with l 0 = 0
.
Return the n
-th element of the given list. The first element (head of the list) is at position 0.
Return the n
-th element of the given list. The first element (head of the list) is at position 0. Return None
if the list is too short.
init len f
is [f 0; f 1; ...; f (len-1)]
, evaluated left to right.
append l0 l1
appends l1
to l0
. Same function as the infix operator @
.
rev_append l1 l2
reverses l1
and concatenates it with l2
. This is equivalent to (
rev
l1) @ l2
.
Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument + length of the longest sub-list).
Same as concat
. Not tail-recursive (length of the argument + length of the longest sub-list).
equal eq [a1; ...; an] [b1; ..; bm]
holds when the two input lists have the same length, and for each pair of elements ai
, bi
at the same position we have eq ai bi
.
Note: the eq
function may be called even if the lists have different length. If you know your equality function is costly, you may want to check compare_lengths
first.
compare cmp [a1; ...; an] [b1; ...; bm]
performs a lexicographic comparison of the two input lists, using the same 'a -> 'a -> int
interface as Stdlib.compare
:
a1 :: l1
is smaller than a2 :: l2
(negative result) if a1
is smaller than a2
, or if they are equal (0 result) and l1
is smaller than l2
[]
is strictly smaller than non-empty listsNote: the cmp
function will be called even if the lists have different lengths.
iter f [a1; ...; an]
applies function f
in turn to [a1; ...; an]
. It is equivalent to f a1; f a2; ...; f an
.
Same as iter
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
map f [a1; ...; an]
applies function f
to a1, ..., an
, and builds the list [f a1; ...; f an]
with the results returned by f
.
Same as map
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
filter_map f l
applies f
to every element of l
, filters out the None
elements and returns the list of the arguments of the Some
elements.
fold_left_map
is a combination of fold_left
and map
that threads an accumulator through calls to f
.
fold_left f init [b1; ...; bn]
is f (... (f (f init b1) b2) ...) bn
.
fold_right f [a1; ...; an] init
is f a1 (f a2 (... (f an init) ...))
. Not tail-recursive.
iter2 f [a1; ...; an] [b1; ...; bn]
calls in turn f a1 b1; ...; f an bn
.
map2 f [a1; ...; an] [b1; ...; bn]
is [f a1 b1; ...; f an bn]
.
fold_left2 f init [a1; ...; an] [b1; ...; bn]
is f (... (f (f init a1 b1) a2 b2) ...) an bn
.
fold_right2 f [a1; ...; an] [b1; ...; bn] init
is f a1 b1 (f a2 b2 (... (f an bn init) ...))
.
for_all f [a1; ...; an]
checks if all elements of the list satisfy the predicate f
. That is, it returns (f a1) && (f a2) && ... && (f an)
for a non-empty list and true
if the list is empty.
exists f [a1; ...; an]
checks if at least one element of the list satisfies the predicate f
. That is, it returns (f a1) || (f a2) || ... || (f an)
for a non-empty list and false
if the list is empty.
Same as for_all
, but for a two-argument predicate.
Same as exists
, but for a two-argument predicate.
find f l
returns the first element of the list l
that satisfies the predicate f
.
find f l
returns the first element of the list l
that satisfies the predicate f
. Returns None
if there is no value that satisfies f
in the list l
.
find_index f xs
returns Some i
, where i
is the index of the first element of the list xs
that satisfies f x
, if there is such an element.
It returns None
if there is no such element.
find_map f l
applies f
to the elements of l
in order, and returns the first result of the form Some v
, or None
if none exist.
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
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 is preserved.
find_all
is another name for filter
.
Same as filter
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
partition f l
returns a pair of lists (l1, l2)
, where l1
is the list of all the elements of l
that satisfy the predicate f
, and l2
is the list of all the elements of l
that do not satisfy f
. The order of the elements in the input list is preserved.
partition_map f l
returns a pair of lists (l1, l2)
such that, for each element x
of the input list l
:
f x
is Left y1
, then y1
is in l1
, andf x
is Right y2
, then y2
is in l2
.The output elements are included in l1
and l2
in the same relative order as the corresponding input elements in l
.
In particular, partition_map (fun x -> if f x then Left x else Right x) l
is equivalent to partition f l
.
assoc a l
returns the value associated with key a
in the list of pairs l
. That is, assoc a [ ...; (a,b); ...] = b
if (a,b)
is the leftmost binding of a
in list l
.
assoc_opt a l
returns the value associated with key a
in the list of pairs l
. That is, assoc_opt a [ ...; (a,b); ...] = Some b
if (a,b)
is the leftmost binding of a
in list l
. Returns None
if there is no value associated with a
in the list l
.
Same as assoc
, but simply return true
if a binding exists, and false
if no bindings exist for the given key.
remove_assoc a l
returns the list of pairs l
without the first pair with key a
, if any. Not tail-recursive.
Transform a list of pairs into a pair of lists: split [(a1,b1); ...; (an,bn)]
is ([a1; ...; an], [b1; ...; bn])
. Not tail-recursive.
Transform a pair of lists into a list of pairs: combine [a1; ...; an] [b1; ...; bn]
is [(a1,b1); ...; (an,bn)]
.
Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, Stdlib.compare
is a suitable comparison function. The resulting list is sorted in increasing order. sort
is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space.
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
, but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order).
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
or stable_sort
, whichever is faster on typical input.
Same as sort
, but also remove duplicates.
Merge two lists: Assuming that l1
and l2
are sorted according to the comparison function cmp
, merge cmp l1 l2
will return a sorted list containing all the elements of l1
and l2
. If several elements compare equal, the elements of l1
will be before the elements of l2
. Not tail-recursive (sum of the lengths of the arguments).
Same as mem
, but uses physical equality instead of structural equality to compare list elements.
Same as assoc
, but uses physical equality instead of structural equality to compare keys.
Same as assoc_opt
, but uses physical equality instead of structural equality to compare keys.
Same as mem_assoc
, but uses physical equality instead of structural equality to compare keys.
Same as remove_assoc
, but uses physical equality instead of structural equality to compare keys. Not tail-recursive.
Stdlib_alerting.ListLabels
include sig ... end
Compare the lengths of two lists. compare_lengths l1 l2
is equivalent to compare (length l1) (length l2)
, except that the computation stops after reaching the end of the shortest list.
Compare the length of a list to an integer. compare_length_with l len
is equivalent to compare (length l) len
, except that the computation stops after at most len
iterations on the list.
is_empty l
is true if and only if l
has no elements. It is equivalent to compare_length_with l 0 = 0
.
Return the n
-th element of the given list. The first element (head of the list) is at position 0.
Return the n
-th element of the given list. The first element (head of the list) is at position 0. Return None
if the list is too short.
init ~len ~f
is [f 0; f 1; ...; f (len-1)]
, evaluated left to right.
append l0 l1
appends l1
to l0
. Same function as the infix operator @
.
rev_append l1 l2
reverses l1
and concatenates it with l2
. This is equivalent to (
rev
l1) @ l2
.
Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument + length of the longest sub-list).
Same as concat
. Not tail-recursive (length of the argument + length of the longest sub-list).
equal eq [a1; ...; an] [b1; ..; bm]
holds when the two input lists have the same length, and for each pair of elements ai
, bi
at the same position we have eq ai bi
.
Note: the eq
function may be called even if the lists have different length. If you know your equality function is costly, you may want to check compare_lengths
first.
compare cmp [a1; ...; an] [b1; ...; bm]
performs a lexicographic comparison of the two input lists, using the same 'a -> 'a -> int
interface as Stdlib.compare
:
a1 :: l1
is smaller than a2 :: l2
(negative result) if a1
is smaller than a2
, or if they are equal (0 result) and l1
is smaller than l2
[]
is strictly smaller than non-empty listsNote: the cmp
function will be called even if the lists have different lengths.
iter ~f [a1; ...; an]
applies function f
in turn to [a1; ...; an]
. It is equivalent to f a1; f a2; ...; f an
.
Same as iter
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
map ~f [a1; ...; an]
applies function f
to a1, ..., an
, and builds the list [f a1; ...; f an]
with the results returned by f
.
Same as map
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
filter_map ~f l
applies f
to every element of l
, filters out the None
elements and returns the list of the arguments of the Some
elements.
fold_left_map
is a combination of fold_left
and map
that threads an accumulator through calls to f
.
fold_left ~f ~init [b1; ...; bn]
is f (... (f (f init b1) b2) ...) bn
.
fold_right ~f [a1; ...; an] ~init
is f a1 (f a2 (... (f an init) ...))
. Not tail-recursive.
iter2 ~f [a1; ...; an] [b1; ...; bn]
calls in turn f a1 b1; ...; f an bn
.
map2 ~f [a1; ...; an] [b1; ...; bn]
is [f a1 b1; ...; f an bn]
.
fold_left2 ~f ~init [a1; ...; an] [b1; ...; bn]
is f (... (f (f init a1 b1) a2 b2) ...) an bn
.
fold_right2 ~f [a1; ...; an] [b1; ...; bn] ~init
is f a1 b1 (f a2 b2 (... (f an bn init) ...))
.
for_all ~f [a1; ...; an]
checks if all elements of the list satisfy the predicate f
. That is, it returns (f a1) && (f a2) && ... && (f an)
for a non-empty list and true
if the list is empty.
exists ~f [a1; ...; an]
checks if at least one element of the list satisfies the predicate f
. That is, it returns (f a1) || (f a2) || ... || (f an)
for a non-empty list and false
if the list is empty.
Same as for_all
, but for a two-argument predicate.
Same as exists
, but for a two-argument predicate.
mem a ~set
is true if and only if a
is equal to an element of set
.
find ~f l
returns the first element of the list l
that satisfies the predicate f
.
find ~f l
returns the first element of the list l
that satisfies the predicate f
. Returns None
if there is no value that satisfies f
in the list l
.
find_index ~f xs
returns Some i
, where i
is the index of the first element of the list xs
that satisfies f x
, if there is such an element.
It returns None
if there is no such element.
find_map ~f l
applies f
to the elements of l
in order, and returns the first result of the form Some v
, or None
if none exist.
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
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 is preserved.
find_all
is another name for filter
.
Same as filter
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
partition ~f l
returns a pair of lists (l1, l2)
, where l1
is the list of all the elements of l
that satisfy the predicate f
, and l2
is the list of all the elements of l
that do not satisfy f
. The order of the elements in the input list is preserved.
partition_map f l
returns a pair of lists (l1, l2)
such that, for each element x
of the input list l
:
f x
is Left y1
, then y1
is in l1
, andf x
is Right y2
, then y2
is in l2
.The output elements are included in l1
and l2
in the same relative order as the corresponding input elements in l
.
In particular, partition_map (fun x -> if f x then Left x else Right x) l
is equivalent to partition f l
.
assoc a l
returns the value associated with key a
in the list of pairs l
. That is, assoc a [ ...; (a,b); ...] = b
if (a,b)
is the leftmost binding of a
in list l
.
assoc_opt a l
returns the value associated with key a
in the list of pairs l
. That is, assoc_opt a [ ...; (a,b); ...] = Some b
if (a,b)
is the leftmost binding of a
in list l
. Returns None
if there is no value associated with a
in the list l
.
Same as assoc
, but simply return true
if a binding exists, and false
if no bindings exist for the given key.
remove_assoc a l
returns the list of pairs l
without the first pair with key a
, if any. Not tail-recursive.
Transform a list of pairs into a pair of lists: split [(a1,b1); ...; (an,bn)]
is ([a1; ...; an], [b1; ...; bn])
. Not tail-recursive.
Transform a pair of lists into a list of pairs: combine [a1; ...; an] [b1; ...; bn]
is [(a1,b1); ...; (an,bn)]
.
Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, Stdlib.compare
is a suitable comparison function. The resulting list is sorted in increasing order. sort
is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space.
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
, but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order).
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
or stable_sort
, whichever is faster on typical input.
Same as sort
, but also remove duplicates.
Merge two lists: Assuming that l1
and l2
are sorted according to the comparison function cmp
, merge ~cmp l1 l2
will return a sorted list containing all the elements of l1
and l2
. If several elements compare equal, the elements of l1
will be before the elements of l2
. Not tail-recursive (sum of the lengths of the arguments).
Same as mem
, but uses physical equality instead of structural equality to compare list elements.
Same as assoc
, but uses physical equality instead of structural equality to compare keys.
Same as assoc_opt
, but uses physical equality instead of structural equality to compare keys.
Same as mem_assoc
, but uses physical equality instead of structural equality to compare keys.
Same as remove_assoc
, but uses physical equality instead of structural equality to compare keys. Not tail-recursive.
Make.H
val hash : t -> int
A hashing function on keys. It must be such that if two keys are equal according to equal
, then they have identical hash values as computed by hash
. Examples: suitable (equal
, hash
) pairs for arbitrary key types include
Hashtbl.Make
Functor building an implementation of the hashtable structure. The functor Hashtbl.Make
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. Since the hash function is not seeded, the create
operation of the result structure always returns non-randomized hash tables.
module H : HashedType
type key = H.t
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
MakeSeeded.H
val seeded_hash : int -> t -> int
A seeded hashing function on keys. The first argument is the seed. It must be the case that if equal x y
is true, then seeded_hash seed x = seeded_hash seed y
for any value of seed
. A suitable choice for seeded_hash
is the function Hashtbl.seeded_hash
below.
Hashtbl.MakeSeeded
Functor building an implementation of the hashtable structure. The functor Hashtbl.MakeSeeded
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. The create
operation of the result structure supports the ~random
optional parameter and returns randomized hash tables if ~random:true
is passed or if randomization is globally on (see Hashtbl.randomize
).
module H : SeededHashedType
type key = H.t
val create : ?random:bool -> int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
MoreLabels.Hashtbl
Hash tables and hash functions.
Hash tables are hashed association tables, with in-place modification. Because most operations on a hash table modify their input, they're more commonly used in imperative code. The lookup of the value associated with a key (see find
, find_opt
) is normally very fast, often faster than the equivalent lookup in Map
.
The functors Make
and MakeSeeded
can be used when performance or flexibility are key. The user provides custom equality and hash functions for the key type, and obtains a custom hash table type for this particular type of key.
Warning a hash table is only as good as the hash function. A bad hash function will turn the table into a degenerate association list, with linear time lookup instead of constant time lookup.
The polymorphic t
hash table is useful in simpler cases or in interactive environments. It uses the polymorphic hash
function defined in the OCaml runtime (at the time of writing, it's SipHash), as well as the polymorphic equality (=)
.
See the examples section.
Unsynchronized accesses
Unsynchronized accesses to a hash table may lead to an invalid hash table state. Thus, concurrent accesses to a hash tables must be synchronized (for instance with a Mutex.t
).
val create : ?random:bool -> int -> ('a, 'b) t
Hashtbl.create n
creates a new, empty hash table, with initial size n
. For best results, n
should be on the order of the expected number of elements that will be in the table. The table grows as needed, so n
is just an initial guess.
The optional ~random
parameter (a boolean) controls whether the internal organization of the hash table is randomized at each execution of Hashtbl.create
or deterministic over all executions.
A hash table that is created with ~random
set to false
uses a fixed hash function (hash
) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down.
A hash table that is created with ~random
set to true
uses the seeded hash function seeded_hash
with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among 2^{30}
different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using fold
or iter
is no longer deterministic: elements are enumerated in different orders at different runs of the program.
If no ~random
parameter is given, hash tables are created in non-random mode by default. This default can be changed either programmatically by calling randomize
or by setting the R
flag in the OCAMLRUNPARAM
environment variable.
val clear : ('a, 'b) t -> unit
Empty a hash table. Use reset
instead of clear
to shrink the size of the bucket table to its initial size.
val reset : ('a, 'b) t -> unit
Empty a hash table and shrink the size of the bucket table to its initial size.
val add : ('a, 'b) t -> key:'a -> data:'b -> unit
Hashtbl.add tbl ~key ~data
adds a binding of key
to data
in table tbl
.
Warning: Previous bindings for key
are not removed, but simply hidden. That is, after performing remove
tbl key
, the previous binding for key
, if any, is restored. (Same behavior as with association lists.)
If you desire the classic behavior of replacing elements, see replace
.
val find : ('a, 'b) t -> 'a -> 'b
Hashtbl.find tbl x
returns the current binding of x
in tbl
, or raises Not_found
if no such binding exists.
val find_opt : ('a, 'b) t -> 'a -> 'b option
Hashtbl.find_opt tbl x
returns the current binding of x
in tbl
, or None
if no such binding exists.
val find_all : ('a, 'b) t -> 'a -> 'b list
Hashtbl.find_all tbl x
returns the list of all data associated with x
in tbl
. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table.
val mem : ('a, 'b) t -> 'a -> bool
Hashtbl.mem tbl x
checks if x
is bound in tbl
.
val remove : ('a, 'b) t -> 'a -> unit
Hashtbl.remove tbl x
removes the current binding of x
in tbl
, restoring the previous binding if it exists. It does nothing if x
is not bound in tbl
.
val replace : ('a, 'b) t -> key:'a -> data:'b -> unit
val iter : f:(key:'a -> data:'b -> unit) -> ('a, 'b) t -> unit
Hashtbl.iter ~f tbl
applies f
to all bindings in table tbl
. f
receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to f
.
The order in which the bindings are passed to f
is unspecified. However, if the table contains several bindings for the same key, they are passed to f
in reverse order of introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.
The behavior is not specified if the hash table is modified by f
during the iteration.
val filter_map_inplace :
+ f:(key:'a -> data:'b -> 'b option) ->
+ ('a, 'b) t ->
+ unit
Hashtbl.filter_map_inplace ~f tbl
applies f
to all bindings in table tbl
and update each binding depending on the result of f
. If f
returns None
, the binding is discarded. If it returns Some new_val
, the binding is update to associate the key to new_val
.
Other comments for iter
apply as well.
val fold :
+ f:(key:'a -> data:'b -> 'acc -> 'acc) ->
+ ('a, 'b) t ->
+ init:'acc ->
+ 'acc
Hashtbl.fold ~f tbl ~init
computes (f kN dN ... (f k1 d1 init)...)
, where k1 ... kN
are the keys of all bindings in tbl
, and d1 ... dN
are the associated values. Each binding is presented exactly once to f
.
The order in which the bindings are passed to f
is unspecified. However, if the table contains several bindings for the same key, they are passed to f
in reverse order of introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.
The behavior is not specified if the hash table is modified by f
during the iteration.
val length : ('a, 'b) t -> int
Hashtbl.length tbl
returns the number of bindings in tbl
. It takes constant time. Multiple bindings are counted once each, so Hashtbl.length
gives the number of times Hashtbl.iter
calls its first argument.
After a call to Hashtbl.randomize()
, hash tables are created in randomized mode by default: create
returns randomized hash tables, unless the ~random:false
optional parameter is given. The same effect can be achieved by setting the R
parameter in the OCAMLRUNPARAM
environment variable.
It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in create
call Hashtbl.randomize()
at initialization time before any domains are created.
Note that once Hashtbl.randomize()
was called, there is no way to revert to the non-randomized default behavior of create
. This is intentional. Non-randomized hash tables can still be created using Hashtbl.create ~random:false
.
Return true
if the tables are currently created in randomized mode by default, false
otherwise.
Return a copy of the given hashtable. Unlike copy
, rebuild
h
re-hashes all the (key, value) entries of the original table h
. The returned hash table is randomized if h
was randomized, or the optional random
parameter is true, or if the default is to create randomized hash tables; see create
for more information.
rebuild
can safely be used to import a hash table built by an old version of the Hashtbl
module, then marshaled to persistent storage. After unmarshaling, apply rebuild
to produce a hash table for the current version of the Hashtbl
module.
type statistics = Stdlib.Hashtbl.statistics = {
num_bindings : int;
num_buckets : int;
Number of buckets in the table.
*)max_bucket_length : int;
Maximal number of bindings per bucket.
*)bucket_histogram : int array;
Histogram of bucket sizes. This array histo
has length max_bucket_length + 1
. The value of histo.(i)
is the number of buckets whose size is i
.
}
val stats : ('a, 'b) t -> statistics
Hashtbl.stats tbl
returns statistics about the table tbl
: number of buckets, size of the biggest bucket, distribution of buckets by size.
val to_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t
Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first.
The behavior is not specified if the hash table is modified during the iteration.
val to_seq_keys : ('a, _) t -> 'a Stdlib.Seq.t
Same as Seq.map fst (to_seq m)
val to_seq_values : (_, 'b) t -> 'b Stdlib.Seq.t
Same as Seq.map snd (to_seq m)
val add_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t -> unit
Add the given bindings to the table, using add
val replace_seq : ('a, 'b) t -> ('a * 'b) Stdlib.Seq.t -> unit
Add the given bindings to the table, using replace
val of_seq : ('a * 'b) Stdlib.Seq.t -> ('a, 'b) t
Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using replace_seq
, which means that if two pairs have the same key, only the latest one will appear in the table.
The functorial interface allows the use of specific comparison and hash functions, either for performance/security concerns, or because keys are not hashable/comparable with the polymorphic builtins.
For instance, one might want to specialize a table for integer keys:
module IntHash =
+ struct
+ type t = int
+ let equal i j = i=j
+ let hash i = i land max_int
+ end
+
+module IntHashtbl = Hashtbl.Make(IntHash)
+
+let h = IntHashtbl.create 17 in
+IntHashtbl.add h 12 "hello"
This creates a new module IntHashtbl
, with a new type 'a
+ IntHashtbl.t
of tables from int
to 'a
. In this example, h
contains string
values so its type is string IntHashtbl.t
.
Note that the new type 'a IntHashtbl.t
is not compatible with the type ('a,'b) Hashtbl.t
of the generic interface. For example, Hashtbl.length h
would not type-check, you must use IntHashtbl.length
.
module type HashedType = sig ... end
The input signature of the functor Make
.
module Make
+ (H : HashedType) :
+ S with type key = H.t and type 'a t = 'a Stdlib.Hashtbl.Make(H).t
Functor building an implementation of the hashtable structure. The functor Hashtbl.Make
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. Since the hash function is not seeded, the create
operation of the result structure always returns non-randomized hash tables.
module type SeededHashedType = sig ... end
The input signature of the functor MakeSeeded
.
module type SeededS = sig ... end
The output signature of the functor MakeSeeded
.
module MakeSeeded
+ (H : SeededHashedType) :
+ SeededS with type key = H.t and type 'a t = 'a Stdlib.Hashtbl.MakeSeeded(H).t
Functor building an implementation of the hashtable structure. The functor Hashtbl.MakeSeeded
returns a structure containing a type key
of keys and a type 'a t
of hash tables associating data of type 'a
to keys of type key
. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument H
instead of generic equality and hashing. The create
operation of the result structure supports the ~random
optional parameter and returns randomized hash tables if ~random:true
is passed or if randomization is globally on (see Hashtbl.randomize
).
Hashtbl.hash x
associates a nonnegative integer to any value of any type. It is guaranteed that if x = y
or Stdlib.compare x y = 0
, then hash x = hash y
. Moreover, hash
always terminates, even on cyclic structures.
A variant of hash
that is further parameterized by an integer seed.
Hashtbl.hash_param meaningful total x
computes a hash value for x
, with the same properties as for hash
. The two extra integer parameters meaningful
and total
give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure x
, stopping after meaningful
meaningful nodes were encountered, or total
nodes (meaningful or not) were encountered. If total
as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of meaningful
and total
means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters meaningful
and total
govern the tradeoff between accuracy and speed. As default choices, hash
and seeded_hash
take meaningful = 10
and total = 100
.
A variant of hash_param
that is further parameterized by an integer seed. Usage: Hashtbl.seeded_hash_param meaningful total seed x
.
(* 0...99 *)
+let seq = Seq.ints 0 |> Seq.take 100
+
+(* build from Seq.t *)
+# let tbl =
+ seq
+ |> Seq.map (fun x -> x, string_of_int x)
+ |> Hashtbl.of_seq
+val tbl : (int, string) Hashtbl.t = <abstr>
+
+# Hashtbl.length tbl
+- : int = 100
+
+# Hashtbl.find_opt tbl 32
+- : string option = Some "32"
+
+# Hashtbl.find_opt tbl 166
+- : string option = None
+
+# Hashtbl.replace tbl 166 "one six six"
+- : unit = ()
+
+# Hashtbl.find_opt tbl 166
+- : string option = Some "one six six"
+
+# Hashtbl.length tbl
+- : int = 101
Given a sequence of elements (here, a Seq.t
), we want to count how many times each distinct element occurs in the sequence. A simple way to do this, assuming the elements are comparable and hashable, is to use a hash table that maps elements to their number of occurrences.
Here we illustrate that principle using a sequence of (ascii) characters (type char
). We use a custom Char_tbl
specialized for char
.
# module Char_tbl = Hashtbl.Make(struct
+ type t = char
+ let equal = Char.equal
+ let hash = Hashtbl.hash
+ end)
+
+(* count distinct occurrences of chars in [seq] *)
+# let count_chars (seq : char Seq.t) : _ list =
+ let counts = Char_tbl.create 16 in
+ Seq.iter
+ (fun c ->
+ let count_c =
+ Char_tbl.find_opt counts c
+ |> Option.value ~default:0
+ in
+ Char_tbl.replace counts c (count_c + 1))
+ seq;
+ (* turn into a list *)
+ Char_tbl.fold (fun c n l -> (c,n) :: l) counts []
+ |> List.sort (fun (c1,_)(c2,_) -> Char.compare c1 c2)
+val count_chars : Char_tbl.key Seq.t -> (Char.t * int) list = <fun>
+
+(* basic seq from a string *)
+# let seq = String.to_seq "hello world, and all the camels in it!"
+val seq : char Seq.t = <fun>
+
+# count_chars seq
+- : (Char.t * int) list =
+[(' ', 7); ('!', 1); (',', 1); ('a', 3); ('c', 1); ('d', 2); ('e', 3);
+ ('h', 2); ('i', 2); ('l', 6); ('m', 1); ('n', 2); ('o', 2); ('r', 1);
+ ('s', 1); ('t', 2); ('w', 1)]
+
+(* "abcabcabc..." *)
+# let seq2 =
+ Seq.cycle (String.to_seq "abc") |> Seq.take 31
+val seq2 : char Seq.t = <fun>
+
+# String.of_seq seq2
+- : String.t = "abcabcabcabcabcabcabcabcabcabca"
+
+# count_chars seq2
+- : (Char.t * int) list = [('a', 11); ('b', 10); ('c', 10)]
Hashtbl.HashedType
The input signature of the functor Make
.
val hash : t -> int
A hashing function on keys. It must be such that if two keys are equal according to equal
, then they have identical hash values as computed by hash
. Examples: suitable (equal
, hash
) pairs for arbitrary key types include
Hashtbl.S
The output signature of the functor Make
.
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
Hashtbl.SeededHashedType
The input signature of the functor MakeSeeded
.
val seeded_hash : int -> t -> int
A seeded hashing function on keys. The first argument is the seed. It must be the case that if equal x y
is true, then seeded_hash seed x = seeded_hash seed y
for any value of seed
. A suitable choice for seeded_hash
is the function Hashtbl.seeded_hash
below.
Hashtbl.SeededS
The output signature of the functor MakeSeeded
.
val create : ?random:bool -> int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
Make.Ord
A total ordering function over the keys. This is a two-argument function f
such that f e1 e2
is zero if the keys e1
and e2
are equal, f e1 e2
is strictly negative if e1
is smaller than e2
, and f e1 e2
is strictly positive if e1
is greater than e2
. Example: a suitable ordering function is the generic structural comparison function Stdlib.compare
.
Map.Make
Functor building an implementation of the map structure given a totally ordered type.
module Ord : OrderedType
type key = Ord.t
The type of the map keys.
val empty : 'a t
The empty map.
add ~key ~data m
returns a map containing the same bindings as m
, plus a binding of key
to data
. If key
was already bound in m
to a value that is physically equal to data
, m
is returned unchanged (the result of the function is then physically equal to m
). Otherwise, the previous binding of key
in m
disappears.
add_to_list ~key ~data m
is m
with key
mapped to l
such that l
is data :: Map.find key m
if key
was bound in m
and [v]
otherwise.
update ~key ~f m
returns a map containing the same bindings as m
, except for the binding of key
. Depending on the value of y
where y
is f (find_opt key m)
, the binding of key
is added, removed or updated. If y
is None
, the binding is removed if it exists; otherwise, if y
is Some z
then key
is associated to z
in the resulting map. If key
was already bound in m
to a value that is physically equal to z
, m
is returned unchanged (the result of the function is then physically equal to m
).
singleton x y
returns the one-element map that contains a binding y
for x
.
remove x m
returns a map containing the same bindings as m
, except for x
which is unbound in the returned map. If x
was not in m
, m
is returned unchanged (the result of the function is then physically equal to m
).
merge ~f m1 m2
computes a map whose keys are a subset of the keys of m1
and of m2
. The presence of each such binding, and the corresponding value, is determined with the function f
. In terms of the find_opt
operation, we have find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)
for any key x
, provided that f x None None = None
.
union ~f m1 m2
computes a map whose keys are a subset of the keys of m1
and of m2
. When the same binding is defined in both arguments, the function f
is used to combine them. This is a special case of merge
: union f m1 m2
is equivalent to merge f' m1 m2
, where
f' _key None None = None
f' _key (Some v) None = Some v
f' _key None (Some v) = Some v
f' key (Some v1) (Some v2) = f key v1 v2
val cardinal : 'a t -> int
Return the number of bindings of a map.
Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering Ord.compare
, where Ord
is the argument given to Map.Make
.
Return the binding with the smallest key in a given map (with respect to the Ord.compare
ordering), or raise Not_found
if the map is empty.
Return the binding with the smallest key in the given map (with respect to the Ord.compare
ordering), or None
if the map is empty.
Same as min_binding
, but returns the binding with the largest key in the given map.
Same as min_binding_opt
, but returns the binding with the largest key in the given map.
Return one binding of the given map, or raise Not_found
if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
Return one binding of the given map, or None
if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
find x m
returns the current value of x
in m
, or raises Not_found
if no binding for x
exists.
find_opt x m
returns Some v
if the current value of x
in m
is v
, or None
if no binding for x
exists.
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.
For example, find_first (fun k -> Ord.compare k x >= 0) m
will return the first binding k, v
of m
where Ord.compare k x >= 0
(intuitively: k >= x
), or raise Not_found
if x
is greater than any element of m
.
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.
find_last ~f m
, where f
is a monotonically decreasing function, returns the binding of m
with the highest key k
such that f k
, or raises Not_found
if no such key exists.
find_last_opt ~f m
, where f
is a monotonically decreasing function, returns an option containing the binding of m
with the highest key k
such that f k
, or None
if no such key exists.
iter ~f m
applies f
to all bindings in map m
. f
receives the key as first argument, and the associated value as second argument. The bindings are passed to f
in increasing order with respect to the ordering over the type of the keys.
fold ~f m ~init
computes (f kN dN ... (f k1 d1 init)...)
, where k1 ... kN
are the keys of all bindings in m
(in increasing order), and d1 ... dN
are the associated data.
map ~f m
returns a map with same domain as m
, where the associated value a
of all bindings of m
has been replaced by the result of the application of f
to a
. The bindings are passed to f
in increasing order with respect to the ordering over the type of the keys.
Same as map
, but the function receives as arguments both the key and the associated value for each binding of the map.
filter ~f m
returns the map with all the bindings in m
that satisfy predicate p
. If every binding in m
satisfies f
, m
is returned unchanged (the result of the function is then physically equal to m
)
filter_map ~f m
applies the function f
to every binding of m
, and builds a map from the results. For each binding (k, v)
in the input map:
f k v
is None
then k
is not in the result,f k v
is Some v'
then the binding (k, v')
is in the output map.For example, the following function on maps whose values are lists
filter_map
+ (fun _k li -> match li with [] -> None | _::tl -> Some tl)
+ m
drops all bindings of m
whose value is an empty list, and pops the first element of each value that is non-empty.
partition ~f m
returns a pair of maps (m1, m2)
, where m1
contains all the bindings of m
that satisfy the predicate f
, and m2
is the map with all the bindings of m
that do not satisfy f
.
split x m
returns a triple (l, data, r)
, where l
is the map with all the bindings of m
whose key is strictly less than x
; r
is the map with all the bindings of m
whose key is strictly greater than x
; data
is None
if m
contains no binding for x
, or Some v
if m
binds v
to x
.
val is_empty : 'a t -> bool
Test whether a map is empty or not.
mem x m
returns true
if m
contains a binding for x
, and false
otherwise.
equal ~cmp m1 m2
tests whether the maps m1
and m2
are equal, that is, contain equal keys and associate them with equal data. cmp
is the equality predicate used to compare the data associated with the keys.
Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps.
for_all ~f m
checks if all the bindings of the map satisfy the predicate f
.
exists ~f m
checks if at least one binding of the map satisfies the predicate f
.
of_list bs
adds the bindings of bs
to the empty map, in list order (if a key is bound twice in bs
the last one takes over).
Iterate on the whole map, in descending order of keys
to_seq_from k m
iterates on a subset of the bindings of m
, in ascending order of keys, from key k
or above.
MoreLabels.Map
Association tables over ordered types.
This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map.
For instance:
module IntPairs =
+ struct
+ type t = int * int
+ let compare (x0,y0) (x1,y1) =
+ match Stdlib.compare x0 x1 with
+ 0 -> Stdlib.compare y0 y1
+ | c -> c
+ end
+
+module PairsMap = Map.Make(IntPairs)
+
+let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world")
This creates a new module PairsMap
, with a new type 'a PairsMap.t
of maps from int * int
to 'a
. In this example, m
contains string
values so its type is string PairsMap.t
.
module type OrderedType = sig ... end
Input signature of the functor Make
.
Map.OrderedType
Input signature of the functor Make
.
A total ordering function over the keys. This is a two-argument function f
such that f e1 e2
is zero if the keys e1
and e2
are equal, f e1 e2
is strictly negative if e1
is smaller than e2
, and f e1 e2
is strictly positive if e1
is greater than e2
. Example: a suitable ordering function is the generic structural comparison function Stdlib.compare
.
Map.S
Output signature of the functor Make
.
val empty : 'a t
The empty map.
add ~key ~data m
returns a map containing the same bindings as m
, plus a binding of key
to data
. If key
was already bound in m
to a value that is physically equal to data
, m
is returned unchanged (the result of the function is then physically equal to m
). Otherwise, the previous binding of key
in m
disappears.
add_to_list ~key ~data m
is m
with key
mapped to l
such that l
is data :: Map.find key m
if key
was bound in m
and [v]
otherwise.
update ~key ~f m
returns a map containing the same bindings as m
, except for the binding of key
. Depending on the value of y
where y
is f (find_opt key m)
, the binding of key
is added, removed or updated. If y
is None
, the binding is removed if it exists; otherwise, if y
is Some z
then key
is associated to z
in the resulting map. If key
was already bound in m
to a value that is physically equal to z
, m
is returned unchanged (the result of the function is then physically equal to m
).
singleton x y
returns the one-element map that contains a binding y
for x
.
remove x m
returns a map containing the same bindings as m
, except for x
which is unbound in the returned map. If x
was not in m
, m
is returned unchanged (the result of the function is then physically equal to m
).
merge ~f m1 m2
computes a map whose keys are a subset of the keys of m1
and of m2
. The presence of each such binding, and the corresponding value, is determined with the function f
. In terms of the find_opt
operation, we have find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)
for any key x
, provided that f x None None = None
.
union ~f m1 m2
computes a map whose keys are a subset of the keys of m1
and of m2
. When the same binding is defined in both arguments, the function f
is used to combine them. This is a special case of merge
: union f m1 m2
is equivalent to merge f' m1 m2
, where
f' _key None None = None
f' _key (Some v) None = Some v
f' _key None (Some v) = Some v
f' key (Some v1) (Some v2) = f key v1 v2
val cardinal : 'a t -> int
Return the number of bindings of a map.
Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering Ord.compare
, where Ord
is the argument given to Map.Make
.
Return the binding with the smallest key in a given map (with respect to the Ord.compare
ordering), or raise Not_found
if the map is empty.
Return the binding with the smallest key in the given map (with respect to the Ord.compare
ordering), or None
if the map is empty.
Same as min_binding
, but returns the binding with the largest key in the given map.
Same as min_binding_opt
, but returns the binding with the largest key in the given map.
Return one binding of the given map, or raise Not_found
if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
Return one binding of the given map, or None
if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
find x m
returns the current value of x
in m
, or raises Not_found
if no binding for x
exists.
find_opt x m
returns Some v
if the current value of x
in m
is v
, or None
if no binding for x
exists.
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.
For example, find_first (fun k -> Ord.compare k x >= 0) m
will return the first binding k, v
of m
where Ord.compare k x >= 0
(intuitively: k >= x
), or raise Not_found
if x
is greater than any element of m
.
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.
find_last ~f m
, where f
is a monotonically decreasing function, returns the binding of m
with the highest key k
such that f k
, or raises Not_found
if no such key exists.
find_last_opt ~f m
, where f
is a monotonically decreasing function, returns an option containing the binding of m
with the highest key k
such that f k
, or None
if no such key exists.
iter ~f m
applies f
to all bindings in map m
. f
receives the key as first argument, and the associated value as second argument. The bindings are passed to f
in increasing order with respect to the ordering over the type of the keys.
fold ~f m ~init
computes (f kN dN ... (f k1 d1 init)...)
, where k1 ... kN
are the keys of all bindings in m
(in increasing order), and d1 ... dN
are the associated data.
map ~f m
returns a map with same domain as m
, where the associated value a
of all bindings of m
has been replaced by the result of the application of f
to a
. The bindings are passed to f
in increasing order with respect to the ordering over the type of the keys.
Same as map
, but the function receives as arguments both the key and the associated value for each binding of the map.
filter ~f m
returns the map with all the bindings in m
that satisfy predicate p
. If every binding in m
satisfies f
, m
is returned unchanged (the result of the function is then physically equal to m
)
filter_map ~f m
applies the function f
to every binding of m
, and builds a map from the results. For each binding (k, v)
in the input map:
f k v
is None
then k
is not in the result,f k v
is Some v'
then the binding (k, v')
is in the output map.For example, the following function on maps whose values are lists
filter_map
+ (fun _k li -> match li with [] -> None | _::tl -> Some tl)
+ m
drops all bindings of m
whose value is an empty list, and pops the first element of each value that is non-empty.
partition ~f m
returns a pair of maps (m1, m2)
, where m1
contains all the bindings of m
that satisfy the predicate f
, and m2
is the map with all the bindings of m
that do not satisfy f
.
split x m
returns a triple (l, data, r)
, where l
is the map with all the bindings of m
whose key is strictly less than x
; r
is the map with all the bindings of m
whose key is strictly greater than x
; data
is None
if m
contains no binding for x
, or Some v
if m
binds v
to x
.
val is_empty : 'a t -> bool
Test whether a map is empty or not.
mem x m
returns true
if m
contains a binding for x
, and false
otherwise.
equal ~cmp m1 m2
tests whether the maps m1
and m2
are equal, that is, contain equal keys and associate them with equal data. cmp
is the equality predicate used to compare the data associated with the keys.
Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps.
for_all ~f m
checks if all the bindings of the map satisfy the predicate f
.
exists ~f m
checks if at least one binding of the map satisfies the predicate f
.
of_list bs
adds the bindings of bs
to the empty map, in list order (if a key is bound twice in bs
the last one takes over).
Iterate on the whole map, in descending order of keys
to_seq_from k m
iterates on a subset of the bindings of m
, in ascending order of keys, from key k
or above.
Make.Ord
A total ordering function over the set elements. This is a two-argument function f
such that f e1 e2
is zero if the elements e1
and e2
are equal, f e1 e2
is strictly negative if e1
is smaller than e2
, and f e1 e2
is strictly positive if e1
is greater than e2
. Example: a suitable ordering function is the generic structural comparison function Stdlib.compare
.
Set.Make
Functor building an implementation of the set structure given a totally ordered type.
module Ord : OrderedType
type elt = Ord.t
The type of the set elements.
val empty : t
The empty set.
add x s
returns a set containing all elements of s
, plus x
. If x
was already in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
remove x s
returns a set containing all elements of s
, except x
. If x
was not in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
val cardinal : t -> int
Return the number of elements of a set.
Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering Ord.compare
, where Ord
is the argument given to Set.Make
.
Return the smallest element of the given set (with respect to the Ord.compare
ordering), or raise Not_found
if the set is empty.
Return the smallest element of the given set (with respect to the Ord.compare
ordering), or None
if the set is empty.
Same as min_elt_opt
, but returns the largest element of the given set.
Return one element of the given set, or raise Not_found
if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
Return one element of the given set, or None
if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
find x s
returns the element of s
equal to x
(according to Ord.compare
), or raise Not_found
if no such element exists.
find_opt x s
returns the element of s
equal to x
(according to Ord.compare
), or None
if no such element exists.
find_first ~f s
, where f
is a monotonically increasing function, returns the lowest element e
of s
such that f e
, or raises Not_found
if no such element exists.
For example, find_first (fun e -> Ord.compare e x >= 0) s
will return the first element e
of s
where Ord.compare e x >= 0
(intuitively: e >= x
), or raise Not_found
if x
is greater than any element of s
.
find_first_opt ~f s
, where f
is a monotonically increasing function, returns an option containing the lowest element e
of s
such that f e
, or None
if no such element exists.
find_last ~f s
, where f
is a monotonically decreasing function, returns the highest element e
of s
such that f e
, or raises Not_found
if no such element exists.
find_last_opt ~f s
, where f
is a monotonically decreasing function, returns an option containing the highest element e
of s
such that f e
, or None
if no such element exists.
iter ~f s
applies f
in turn to all elements of s
. The elements of s
are presented to f
in increasing order with respect to the ordering over the type of the elements.
fold ~f s init
computes (f xN ... (f x2 (f x1 init))...)
, where x1 ... xN
are the elements of s
, in increasing order.
map ~f s
is the set whose elements are f a0
,f a1
... f
+ aN
, where a0
,a1
...aN
are the elements of s
.
The elements are passed to f
in increasing order with respect to the ordering over the type of the elements.
If no element of s
is changed by f
, s
is returned unchanged. (If each output of f
is physically equal to its input, the returned set is physically equal to s
.)
filter ~f s
returns the set of all elements in s
that satisfy predicate f
. If f
satisfies every element in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
filter_map ~f s
returns the set of all v
such that f x = Some v
for some element x
of s
.
For example,
filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s
is the set of halves of the even elements of s
.
If no element of s
is changed or dropped by f
(if f x = Some x
for each element x
), then s
is returned unchanged: the result of the function is then physically equal to s
.
partition ~f s
returns a pair of sets (s1, s2)
, where s1
is the set of all the elements of s
that satisfy the predicate f
, and s2
is the set of all the elements of s
that do not satisfy f
.
split x s
returns a triple (l, present, r)
, where l
is the set of elements of s
that are strictly less than x
; r
is the set of elements of s
that are strictly greater than x
; present
is false
if s
contains no element equal to x
, or true
if s
contains an element equal to x
.
val is_empty : t -> bool
Test whether a set is empty or not.
equal s1 s2
tests whether the sets s1
and s2
are equal, that is, contain equal elements.
Total ordering between sets. Can be used as the ordering function for doing sets of sets.
for_all ~f s
checks if all elements of the set satisfy the predicate f
.
exists ~f s
checks if at least one element of the set satisfies the predicate f
.
of_list l
creates a set from a list of elements. This is usually more efficient than folding add
over the list, except perhaps for lists with many duplicated elements.
to_seq_from x s
iterates on a subset of the elements of s
in ascending order, from x
or above.
MoreLabels.Set
Sets over ordered types.
This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance.
The Make
functor constructs implementations for any type, given a compare
function. For instance:
module IntPairs =
+ struct
+ type t = int * int
+ let compare (x0,y0) (x1,y1) =
+ match Stdlib.compare x0 x1 with
+ 0 -> Stdlib.compare y0 y1
+ | c -> c
+ end
+
+module PairsSet = Set.Make(IntPairs)
+
+let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13))
This creates a new module PairsSet
, with a new type PairsSet.t
of sets of int * int
.
module type OrderedType = sig ... end
Input signature of the functor Make
.
Set.OrderedType
Input signature of the functor Make
.
A total ordering function over the set elements. This is a two-argument function f
such that f e1 e2
is zero if the elements e1
and e2
are equal, f e1 e2
is strictly negative if e1
is smaller than e2
, and f e1 e2
is strictly positive if e1
is greater than e2
. Example: a suitable ordering function is the generic structural comparison function Stdlib.compare
.
Set.S
Output signature of the functor Make
.
val empty : t
The empty set.
add x s
returns a set containing all elements of s
, plus x
. If x
was already in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
remove x s
returns a set containing all elements of s
, except x
. If x
was not in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
val cardinal : t -> int
Return the number of elements of a set.
Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering Ord.compare
, where Ord
is the argument given to Set.Make
.
Return the smallest element of the given set (with respect to the Ord.compare
ordering), or raise Not_found
if the set is empty.
Return the smallest element of the given set (with respect to the Ord.compare
ordering), or None
if the set is empty.
Same as min_elt_opt
, but returns the largest element of the given set.
Return one element of the given set, or raise Not_found
if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
Return one element of the given set, or None
if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
find x s
returns the element of s
equal to x
(according to Ord.compare
), or raise Not_found
if no such element exists.
find_opt x s
returns the element of s
equal to x
(according to Ord.compare
), or None
if no such element exists.
find_first ~f s
, where f
is a monotonically increasing function, returns the lowest element e
of s
such that f e
, or raises Not_found
if no such element exists.
For example, find_first (fun e -> Ord.compare e x >= 0) s
will return the first element e
of s
where Ord.compare e x >= 0
(intuitively: e >= x
), or raise Not_found
if x
is greater than any element of s
.
find_first_opt ~f s
, where f
is a monotonically increasing function, returns an option containing the lowest element e
of s
such that f e
, or None
if no such element exists.
find_last ~f s
, where f
is a monotonically decreasing function, returns the highest element e
of s
such that f e
, or raises Not_found
if no such element exists.
find_last_opt ~f s
, where f
is a monotonically decreasing function, returns an option containing the highest element e
of s
such that f e
, or None
if no such element exists.
iter ~f s
applies f
in turn to all elements of s
. The elements of s
are presented to f
in increasing order with respect to the ordering over the type of the elements.
fold ~f s init
computes (f xN ... (f x2 (f x1 init))...)
, where x1 ... xN
are the elements of s
, in increasing order.
map ~f s
is the set whose elements are f a0
,f a1
... f
+ aN
, where a0
,a1
...aN
are the elements of s
.
The elements are passed to f
in increasing order with respect to the ordering over the type of the elements.
If no element of s
is changed by f
, s
is returned unchanged. (If each output of f
is physically equal to its input, the returned set is physically equal to s
.)
filter ~f s
returns the set of all elements in s
that satisfy predicate f
. If f
satisfies every element in s
, s
is returned unchanged (the result of the function is then physically equal to s
).
filter_map ~f s
returns the set of all v
such that f x = Some v
for some element x
of s
.
For example,
filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s
is the set of halves of the even elements of s
.
If no element of s
is changed or dropped by f
(if f x = Some x
for each element x
), then s
is returned unchanged: the result of the function is then physically equal to s
.
partition ~f s
returns a pair of sets (s1, s2)
, where s1
is the set of all the elements of s
that satisfy the predicate f
, and s2
is the set of all the elements of s
that do not satisfy f
.
split x s
returns a triple (l, present, r)
, where l
is the set of elements of s
that are strictly less than x
; r
is the set of elements of s
that are strictly greater than x
; present
is false
if s
contains no element equal to x
, or true
if s
contains an element equal to x
.
val is_empty : t -> bool
Test whether a set is empty or not.
equal s1 s2
tests whether the sets s1
and s2
are equal, that is, contain equal elements.
Total ordering between sets. Can be used as the ordering function for doing sets of sets.
for_all ~f s
checks if all elements of the set satisfy the predicate f
.
exists ~f s
checks if at least one element of the set satisfies the predicate f
.
of_list l
creates a set from a list of elements. This is usually more efficient than folding add
over the list, except perhaps for lists with many duplicated elements.
to_seq_from x s
iterates on a subset of the elements of s
in ascending order, from x
or above.
Stdlib_alerting.MoreLabels
Printexc.Slot
type t = backtrace_slot
val is_raise : t -> bool
is_raise slot
is true
when slot
refers to a raising point in the code, and false
when it comes from a simple function call.
val is_inline : t -> bool
is_inline slot
is true
when slot
refers to a call that got inlined by the compiler, and false
when it comes from any other context.
location slot
returns the location information of the slot, if available, and None
otherwise.
Some possible reasons for failing to return a location are as follow:
-g
)val name : t -> string option
name slot
returns the name of the function or definition enclosing the location referred to by the slot.
name slot
returns None if the name is unavailable, which may happen for the same reasons as location
returning None.
val format : int -> t -> string option
format pos slot
returns the string representation of slot
as raw_backtrace_to_string
would format it, assuming it is the pos
-th element of the backtrace: the 0
-th element is pretty-printed differently than the others.
Whole-backtrace printing functions also skip some uninformative slots; in that case, format pos slot
returns None
.
Stdlib_alerting.Printexc
include sig ... end
Printexc.to_string_default e
returns a string representation of the exception e
, ignoring all registered exception printers.
Printexc.to_string e
returns a string representation of the exception e
.
Printexc.print fn x
applies fn
to x
and returns the result. If the evaluation of fn x
raises any exception, the name of the exception is printed on standard error output, and the exception is raised again. The typical use is to catch and report exceptions that escape a function application.
Printexc.catch fn x
is similar to Printexc.print
, but aborts the program with exit code 2 after printing the uncaught exception. This function is deprecated: the runtime system is now able to print uncaught exceptions as precisely as Printexc.catch
does. Moreover, calling Printexc.catch
makes it harder to track the location of the exception using the debugger or the stack backtrace facility. So, do not use Printexc.catch
in new code.
Printexc.print_backtrace oc
prints an exception backtrace on the output channel oc
. The backtrace lists the program locations where the most-recently raised exception was raised and where it was propagated through function calls.
If the call is not inside an exception handler, the returned backtrace is unspecified. If the call is after some exception-catching code (before in the handler, or in a when-guard during the matching of the exception handler), the backtrace may correspond to a later exception than the handled one.
Printexc.get_backtrace ()
returns a string containing the same exception backtrace that Printexc.print_backtrace
would print. Same restriction usage than print_backtrace
.
Printexc.record_backtrace b
turns recording of exception backtraces on (if b = true
) or off (if b = false
). Initially, backtraces are not recorded, unless the b
flag is given to the program through the OCAMLRUNPARAM
variable.
Printexc.backtrace_status()
returns true
if exception backtraces are currently recorded, false
if not.
Printexc.register_printer fn
registers fn
as an exception printer. The printer should return None
or raise an exception if it does not know how to convert the passed exception, and Some
+ s
with s
the resulting string if it can convert the passed exception. Exceptions raised by the printer are ignored.
When converting an exception into a string, the printers will be invoked in the reverse order of their registrations, until a printer returns a Some s
value (if no such printer exists, the runtime will use a generic printer).
When using this mechanism, one should be aware that an exception backtrace is attached to the thread that saw it raised, rather than to the exception itself. Practically, it means that the code related to fn
should not use the backtrace if it has itself raised an exception before.
Printexc.use_printers e
returns None
if there are no registered printers and Some s
with else as the resulting string otherwise.
The type raw_backtrace
stores a backtrace in a low-level format, which can be converted to usable form using raw_backtrace_entries
and backtrace_slots_of_raw_entry
below.
Converting backtraces to backtrace_slot
s is slower than capturing the backtraces. If an application processes many backtraces, it can be useful to use raw_backtrace
to avoid or delay conversion.
Raw backtraces cannot be marshalled. If you need marshalling, you should use the array returned by the backtrace_slots
function of the next section.
A raw_backtrace_entry
is an element of a raw_backtrace
.
Each raw_backtrace_entry
is an opaque integer, whose value is not stable between different programs, or even between different runs of the same binary.
A raw_backtrace_entry
can be converted to a usable form using backtrace_slots_of_raw_entry
below. Note that, due to inlining, a single raw_backtrace_entry
may convert to several backtrace_slot
s. Since the values of a raw_backtrace_entry
are not stable, they cannot be marshalled. If they are to be converted, the conversion must be done by the process that generated them.
Again due to inlining, there may be multiple distinct raw_backtrace_entry values that convert to equal backtrace_slot
s. However, if two raw_backtrace_entry
s are equal as integers, then they represent the same backtrace_slot
s.
val raw_backtrace_entries : raw_backtrace -> raw_backtrace_entry array
val get_raw_backtrace : unit -> raw_backtrace
Printexc.get_raw_backtrace ()
returns the same exception backtrace that Printexc.print_backtrace
would print, but in a raw format. Same restriction usage than print_backtrace
.
val print_raw_backtrace : Stdlib.out_channel -> raw_backtrace -> unit
Print a raw backtrace in the same format Printexc.print_backtrace
uses.
val raw_backtrace_to_string : raw_backtrace -> string
Return a string from a raw backtrace, in the same format Printexc.get_backtrace
uses.
val raise_with_backtrace : exn -> raw_backtrace -> 'a
Reraise the exception using the given raw_backtrace for the origin of the exception
val get_callstack : int -> raw_backtrace
Printexc.get_callstack n
returns a description of the top of the call stack on the current program point (for the current thread), with at most n
entries. (Note: this function is not related to exceptions at all, despite being part of the Printexc
module.)
val default_uncaught_exception_handler : exn -> raw_backtrace -> unit
Printexc.default_uncaught_exception_handler
prints the exception and backtrace on standard error output.
val set_uncaught_exception_handler : (exn -> raw_backtrace -> unit) -> unit
Printexc.set_uncaught_exception_handler fn
registers fn
as the handler for uncaught exceptions. The default handler is Printexc.default_uncaught_exception_handler
.
Note that when fn
is called all the functions registered with Stdlib.at_exit
have already been called. Because of this you must make sure any output channel fn
writes on is flushed.
Also note that exceptions raised by user code in the interactive toplevel are not passed to this function as they are caught by the toplevel itself.
If fn
raises an exception, both the exceptions passed to fn
and raised by fn
will be printed with their respective backtrace.
val backtrace_slots : raw_backtrace -> backtrace_slot array option
Returns the slots of a raw backtrace, or None
if none of them contain useful information.
In the return array, the slot at index 0
corresponds to the most recent function call, raise, or primitive get_backtrace
call in the trace.
Some possible reasons for returning None
are as follow:
-g
)ocamlc -g
)val backtrace_slots_of_raw_entry :
+ raw_backtrace_entry ->
+ backtrace_slot array option
Returns the slots of a single raw backtrace entry, or None
if this entry lacks debug information.
Slots are returned in the same order as backtrace_slots
: the slot at index 0
is the most recent call, raise, or primitive, and subsequent slots represent callers.
The type of location information found in backtraces. start_char
and end_char
are positions relative to the beginning of the line.
module Slot : sig ... end
This type is used to iterate over the slots of a raw_backtrace
. For most purposes, backtrace_slots_of_raw_entry
is easier to use.
Like raw_backtrace_entry
, values of this type are process-specific and must absolutely not be marshalled, and are unsafe to use for this reason (marshalling them may not fail, but un-marshalling and using the result will result in undefined behavior).
Elements of this type can still be compared and hashed: when two elements are equal, then they represent the same source location (the converse is not necessarily true in presence of inlining, for example).
val raw_backtrace_length : raw_backtrace -> int
raw_backtrace_length bckt
returns the number of slots in the backtrace bckt
.
val get_raw_backtrace_slot : raw_backtrace -> int -> raw_backtrace_slot
get_raw_backtrace_slot bckt pos
returns the slot in position pos
in the backtrace bckt
.
val convert_raw_backtrace_slot : raw_backtrace_slot -> backtrace_slot
Extracts the user-friendly backtrace_slot
from a low-level raw_backtrace_slot
.
val get_raw_backtrace_next_slot :
+ raw_backtrace_slot ->
+ raw_backtrace_slot option
get_raw_backtrace_next_slot slot
returns the next slot inlined, if any.
Sample code to iterate over all frames (inlined and non-inlined):
(* Iterate over inlined frames *)
+let rec iter_raw_backtrace_slot f slot =
+ f slot;
+ match get_raw_backtrace_next_slot slot with
+ | None -> ()
+ | Some slot' -> iter_raw_backtrace_slot f slot'
+
+(* Iterate over stack frames *)
+let iter_raw_backtrace f bt =
+ for i = 0 to raw_backtrace_length bt - 1 do
+ iter_raw_backtrace_slot f (get_raw_backtrace_slot bt i)
+ done
Printexc.exn_slot_id
returns an integer which uniquely identifies the constructor used to create the exception value exn
(in the current runtime).
Printexc.exn_slot_name exn
returns the internal name of the constructor used to create the exception value exn
.
Stdlib_alerting.Printf
include sig ... end
Same as Printf.fprintf
, but instead of printing on an output channel, return a string containing the result of formatting the arguments.
Same as sprintf
above, but instead of returning the string, passes it to the first argument.
fprintf outchan format arg1 ... argN
formats the arguments arg1
to argN
according to the format string format
, and outputs the resulting string on the channel outchan
.
The format string is a character string which contains two types of objects: plain characters, which are simply copied to the output channel, and conversion specifications, each of which causes conversion and printing of arguments.
Conversion specifications have the following form:
% [flags] [width] [.precision] type
In short, a conversion specification consists in the %
character, followed by optional modifiers and a type which is made of one or two characters.
The types and their meanings are:
d
, i
: convert an integer argument to signed decimal. The flag #
adds underscores to large values for readability.u
, n
, l
, L
, or N
: convert an integer argument to unsigned decimal. Warning: n
, l
, L
, and N
are used for scanf
, and should not be used for printf
. The flag #
adds underscores to large values for readability.x
: convert an integer argument to unsigned hexadecimal, using lowercase letters. The flag #
adds a 0x
prefix to non zero values.X
: convert an integer argument to unsigned hexadecimal, using uppercase letters. The flag #
adds a 0X
prefix to non zero values.o
: convert an integer argument to unsigned octal. The flag #
adds a 0
prefix to non zero values.s
: insert a string argument.S
: convert a string argument to OCaml syntax (double quotes, escapes).c
: insert a character argument.C
: convert a character argument to OCaml syntax (single quotes, escapes).f
: convert a floating-point argument to decimal notation, in the style dddd.ddd
.F
: convert a floating-point argument to OCaml syntax (dddd.
or dddd.ddd
or d.ddd e+-dd
). Converts to hexadecimal with the #
flag (see h
).e
or E
: convert a floating-point argument to decimal notation, in the style d.ddd e+-dd
(mantissa and exponent).g
or G
: convert a floating-point argument to decimal notation, in style f
or e
, E
(whichever is more compact). Moreover, any trailing zeros are removed from the fractional part of the result and the decimal-point character is removed if there is no fractional part remaining.h
or H
: convert a floating-point argument to hexadecimal notation, in the style 0xh.hhhh p+-dd
(hexadecimal mantissa, exponent in decimal and denotes a power of 2).B
: convert a boolean argument to the string true
or false
b
: convert a boolean argument (deprecated; do not use in new programs).ld
, li
, lu
, lx
, lX
, lo
: convert an int32
argument to the format specified by the second letter (decimal, hexadecimal, etc).nd
, ni
, nu
, nx
, nX
, no
: convert a nativeint
argument to the format specified by the second letter.Ld
, Li
, Lu
, Lx
, LX
, Lo
: convert an int64
argument to the format specified by the second letter.a
: user-defined printer. Take two arguments and apply the first one to outchan
(the current output channel) and to the second argument. The first argument must therefore have type out_channel -> 'b -> unit
and the second 'b
. The output produced by the function is inserted in the output of fprintf
at the current point.t
: same as %a
, but take only one argument (with type out_channel -> unit
) and apply it to outchan
.\{ fmt %\}
: convert a format string argument to its type digest. The argument must have the same type as the internal format string fmt
.( fmt %)
: format string substitution. Take a format string argument and substitute it to the internal format string fmt
to print following arguments. The argument must have the same type as the internal format string fmt
.!
: take no argument and flush the output.%
: take no argument and output one %
character.\@
: take no argument and output one \@
character.,
: take no argument and output nothing: a no-op delimiter for conversion specifications.The optional flags
are:
-
: left-justify the output (default is right justification).0
: for numerical conversions, pad with zeroes instead of spaces.+
: for signed numerical conversions, prefix number with a +
sign if positive.#
: request an alternate formatting style for the integer types and the floating-point type F
.The optional width
is an integer indicating the minimal width of the result. For instance, %6d
prints an integer, prefixing it with spaces to fill at least 6 characters.
The optional precision
is a dot .
followed by an integer indicating how many digits follow the decimal point in the %f
, %e
, %E
, %h
, and %H
conversions or the maximum number of significant digits to appear for the %F
, %g
and %G
conversions. For instance, %.4f
prints a float
with 4 fractional digits.
The integer in a width
or precision
can also be specified as *
, in which case an extra integer argument is taken to specify the corresponding width
or precision
. This integer argument precedes immediately the argument to print. For instance, %.*f
prints a float
with as many fractional digits as the value of the argument given before the float.
Same as Printf.fprintf
, but output on stdout
.
Same as Printf.fprintf
, but output on stderr
.
Same as Printf.fprintf
, but does not print anything. Useful to ignore some material when conditionally printing.
val kfprintf :
+ (Stdlib.out_channel -> 'd) ->
+ Stdlib.out_channel ->
+ ('a, Stdlib.out_channel, unit, 'd) Stdlib.format4 ->
+ 'a
Same as fprintf
, but instead of returning immediately, passes the out channel to its first argument at the end of printing.
Same as kfprintf
above, but does not print anything. Useful to ignore some material when conditionally printing.
Same as Printf.fprintf
, but instead of printing on an output channel, append the formatted arguments to the given extensible buffer (see module Buffer
).
Same as Printf.bprintf
, but does not print anything. Useful to ignore some material when conditionally printing.
Scanf.Scanning
Stdlib_alerting.Scanf
module Scanning : sig ... end
include sig ... end
type ('a, 'b, 'c, 'd) scanner =
+ ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd, 'd) Stdlib.format6 ->
+ 'c
The type of formatted input scanners: ('a, 'b, 'c, 'd) scanner
is the type of a formatted input function that reads from some formatted input channel according to some format string; more precisely, if scan
is some formatted input function, then scan
+ ic fmt f
applies f
to all the arguments specified by format string fmt
, when scan
has read those arguments from the Scanning.in_channel
formatted input channel ic
.
For instance, the Scanf.scanf
function below has type ('a, 'b, 'c, 'd) scanner
, since it is a formatted input function that reads from Scanning.stdin
: scanf fmt f
applies f
to the arguments specified by fmt
, reading those arguments from Stdlib.stdin
as expected.
If the format fmt
has some %r
indications, the corresponding formatted input functions must be provided before receiver function f
. For instance, if read_elem
is an input function for values of type t
, then bscanf ic "%r;" read_elem f
reads a value v
of type t
followed by a ';'
character, and returns f v
.
type ('a, 'b, 'c, 'd) scanner_opt =
+ ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd option, 'd) Stdlib.format6 ->
+ 'c
When the input can not be read according to the format string specification, formatted input functions typically raise exception Scan_failure
.
val sscanf : string -> ('a, 'b, 'c, 'd) scanner
Same as Scanf.bscanf
, but reads from the given string.
val sscanf_opt : string -> ('a, 'b, 'c, 'd) scanner_opt
Same as Scanf.sscanf
, but returns None
in case of scanning failure.
val ksscanf :
+ string ->
+ (Scanning.in_channel -> exn -> 'd) ->
+ ('a, 'b, 'c, 'd) scanner
Same as Scanf.kscanf
but reads from the given string.
val sscanf_format :
+ string ->
+ ('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6 ->
+ (('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6 -> 'g) ->
+ 'g
Same as Scanf.bscanf_format
, but reads from the given string.
val format_from_string :
+ string ->
+ ('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6 ->
+ ('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6
format_from_string s fmt
converts a string argument to a format string, according to the given format string fmt
.
unescaped s
return a copy of s
with escape sequences (according to the lexical conventions of OCaml) replaced by their corresponding special characters. More precisely, Scanf.unescaped
has the following property: for all string s
, Scanf.unescaped (String.escaped s) = s
.
Always return a copy of the argument, even if there is no escape sequence in the argument.
val bscanf : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner
val bscanf_opt : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner_opt
Same as Scanf.bscanf
, but returns None
in case of scanning failure.
val scanf : ('a, 'b, 'c, 'd) scanner
Same as Scanf.bscanf
, but reads from the predefined formatted input channel Scanf.Scanning.stdin
that is connected to Stdlib.stdin
.
val scanf_opt : ('a, 'b, 'c, 'd) scanner_opt
Same as Scanf.scanf
, but returns None
in case of scanning failure.
val kscanf :
+ Scanning.in_channel ->
+ (Scanning.in_channel -> exn -> 'd) ->
+ ('a, 'b, 'c, 'd) scanner
Same as Scanf.bscanf
, but takes an additional function argument ef
that is called in case of error: if the scanning process or some conversion fails, the scanning function aborts and calls the error handling function ef
with the formatted input channel and the exception that aborted the scanning process as arguments.
val bscanf_format :
+ Scanning.in_channel ->
+ ('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6 ->
+ (('a, 'b, 'c, 'd, 'e, 'f) Stdlib.format6 -> 'g) ->
+ 'g
bscanf_format ic fmt f
reads a format string token from the formatted input channel ic
, according to the given format string fmt
, and applies f
to the resulting format string value.
Stdlib_alerting.Seq
include sig ... end
type 'a t = unit -> 'a node
A sequence xs
of type 'a t
is a delayed list of elements of type 'a
. Such a sequence is queried by performing a function application xs()
. This function application returns a node, allowing the caller to determine whether the sequence is empty or nonempty, and in the latter case, to obtain its head and tail.
A node is either Nil
, which means that the sequence is empty, or Cons (x, xs)
, which means that x
is the first element of the sequence and that xs
is the remainder of the sequence.
val is_empty : 'a t -> bool
is_empty xs
determines whether the sequence xs
is empty.
It is recommended that the sequence xs
be persistent. Indeed, is_empty xs
demands the head of the sequence xs
, so, if xs
is ephemeral, it may be the case that xs
cannot be used any more after this call has taken place.
If xs
is empty, then uncons xs
is None
.
If xs
is nonempty, then uncons xs
is Some (x, ys)
where x
is the head of the sequence and ys
its tail.
val length : 'a t -> int
length xs
is the length of the sequence xs
.
The sequence xs
must be finite.
val iter : ('a -> unit) -> 'a t -> unit
iter f xs
invokes f x
successively for every element x
of the sequence xs
, from left to right.
It terminates only if the sequence xs
is finite.
val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc
fold_left f _ xs
invokes f _ x
successively for every element x
of the sequence xs
, from left to right.
An accumulator of type 'a
is threaded through the calls to f
.
It terminates only if the sequence xs
is finite.
val iteri : (int -> 'a -> unit) -> 'a t -> unit
iteri f xs
invokes f i x
successively for every element x
located at index i
in the sequence xs
.
It terminates only if the sequence xs
is finite.
iteri f xs
is equivalent to iter (fun (i, x) -> f i x) (zip (ints 0) xs)
.
val fold_lefti : ('acc -> int -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc
fold_lefti f _ xs
invokes f _ i x
successively for every element x
located at index i
of the sequence xs
.
An accumulator of type 'b
is threaded through the calls to f
.
It terminates only if the sequence xs
is finite.
fold_lefti f accu xs
is equivalent to fold_left (fun accu (i, x) -> f accu i x) accu (zip (ints 0) xs)
.
val for_all : ('a -> bool) -> 'a t -> bool
for_all p xs
determines whether all elements x
of the sequence xs
satisfy p x
.
The sequence xs
must be finite.
val exists : ('a -> bool) -> 'a t -> bool
exists xs p
determines whether at least one element x
of the sequence xs
satisfies p x
.
The sequence xs
must be finite.
val find : ('a -> bool) -> 'a t -> 'a option
find p xs
returns Some x
, where x
is the first element of the sequence xs
that satisfies p x
, if there is such an element.
It returns None
if there is no such element.
The sequence xs
must be finite.
val find_index : ('a -> bool) -> 'a t -> int option
find_index p xs
returns Some i
, where i
is the index of the first element of the sequence xs
that satisfies p x
, if there is such an element.
It returns None
if there is no such element.
The sequence xs
must be finite.
val find_map : ('a -> 'b option) -> 'a t -> 'b option
find_map f xs
returns Some y
, where x
is the first element of the sequence xs
such that f x = Some _
, if there is such an element, and where y
is defined by f x = Some y
.
It returns None
if there is no such element.
The sequence xs
must be finite.
val find_mapi : (int -> 'a -> 'b option) -> 'a t -> 'b option
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
The sequence xs
must be finite.
iter2 f xs ys
invokes f x y
successively for every pair (x, y)
of elements drawn synchronously from the sequences xs
and ys
.
If the sequences xs
and ys
have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
Iteration terminates only if at least one of the sequences xs
and ys
is finite.
iter2 f xs ys
is equivalent to iter (fun (x, y) -> f x y) (zip xs ys)
.
fold_left2 f _ xs ys
invokes f _ x y
successively for every pair (x, y)
of elements drawn synchronously from the sequences xs
and ys
.
An accumulator of type 'a
is threaded through the calls to f
.
If the sequences xs
and ys
have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
Iteration terminates only if at least one of the sequences xs
and ys
is finite.
fold_left2 f accu xs ys
is equivalent to fold_left (fun accu (x, y) -> f accu x y) (zip xs ys)
.
for_all2 p xs ys
determines whether all pairs (x, y)
of elements drawn synchronously from the sequences xs
and ys
satisfy p x y
.
If the sequences xs
and ys
have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. In particular, if xs
or ys
is empty, then for_all2 p xs ys
is true. This is where for_all2
and equal
differ: equal eq xs ys
can be true only if xs
and ys
have the same length.
At least one of the sequences xs
and ys
must be finite.
for_all2 p xs ys
is equivalent to for_all (fun b -> b) (map2 p xs ys)
.
exists2 p xs ys
determines whether some pair (x, y)
of elements drawn synchronously from the sequences xs
and ys
satisfies p x y
.
If the sequences xs
and ys
have different lengths, then iteration must stop as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
At least one of the sequences xs
and ys
must be finite.
exists2 p xs ys
is equivalent to exists (fun b -> b) (map2 p xs ys)
.
Provided the function eq
defines an equality on elements, equal eq xs ys
determines whether the sequences xs
and ys
are pointwise equal.
At least one of the sequences xs
and ys
must be finite.
Provided the function cmp
defines a preorder on elements, compare cmp xs ys
compares the sequences xs
and ys
according to the lexicographic preorder.
For more details on comparison functions, see Array.sort
.
At least one of the sequences xs
and ys
must be finite.
val empty : 'a t
empty
is the empty sequence. It has no elements. Its length is 0.
val return : 'a -> 'a t
return x
is the sequence whose sole element is x
. Its length is 1.
cons x xs
is the sequence that begins with the element x
, followed with the sequence xs
.
Writing cons (f()) xs
causes the function call f()
to take place immediately. For this call to be delayed until the sequence is queried, one must instead write (fun () -> Cons(f(), xs))
.
val init : int -> (int -> 'a) -> 'a t
init n f
is the sequence f 0; f 1; ...; f (n-1)
.
n
must be nonnegative.
If desired, the infinite sequence f 0; f 1; ...
can be defined as map f (ints 0)
.
val unfold : ('b -> ('a * 'b) option) -> 'b -> 'a t
unfold
constructs a sequence out of a step function and an initial state.
If f u
is None
then unfold f u
is the empty sequence. If f u
is Some (x, u')
then unfold f u
is the nonempty sequence cons x (unfold f u')
.
For example, unfold (function [] -> None | h :: t -> Some (h, t)) l
is equivalent to List.to_seq l
.
val repeat : 'a -> 'a t
repeat x
is the infinite sequence where the element x
is repeated indefinitely.
repeat x
is equivalent to cycle (return x)
.
val forever : (unit -> 'a) -> 'a t
forever f
is an infinite sequence where every element is produced (on demand) by the function call f()
.
For instance, forever Random.bool
is an infinite sequence of random bits.
forever f
is equivalent to map f (repeat ())
.
cycle xs
is the infinite sequence that consists of an infinite number of repetitions of the sequence xs
.
If xs
is an empty sequence, then cycle xs
is empty as well.
Consuming (a prefix of) the sequence cycle xs
once can cause the sequence xs
to be consumed more than once. Therefore, xs
must be persistent.
val iterate : ('a -> 'a) -> 'a -> 'a t
iterate f x
is the infinite sequence whose elements are x
, f x
, f (f x)
, and so on.
In other words, it is the orbit of the function f
, starting at x
.
map f xs
is the image of the sequence xs
through the transformation f
.
If xs
is the sequence x0; x1; ...
then map f xs
is the sequence f x0; f x1; ...
.
mapi
is analogous to map
, but applies the function f
to an index and an element.
mapi f xs
is equivalent to map2 f (ints 0) xs
.
filter p xs
is the sequence of the elements x
of xs
that satisfy p x
.
In other words, filter p xs
is the sequence xs
, deprived of the elements x
such that p x
is false.
filter_map f xs
is the sequence of the elements y
such that f x = Some y
, where x
ranges over xs
.
filter_map f xs
is equivalent to map Option.get (filter Option.is_some (map f xs))
.
If xs
is a sequence [x0; x1; x2; ...]
, then scan f a0 xs
is a sequence of accumulators [a0; a1; a2; ...]
where a1
is f a0 x0
, a2
is f a1 x1
, and so on.
Thus, scan f a0 xs
is conceptually related to fold_left f a0 xs
. However, instead of performing an eager iteration and immediately returning the final accumulator, it returns a sequence of accumulators.
For instance, scan (+) 0
transforms a sequence of integers into the sequence of its partial sums.
If xs
has length n
then scan f a0 xs
has length n+1
.
take n xs
is the sequence of the first n
elements of xs
.
If xs
has fewer than n
elements, then take n xs
is equivalent to xs
.
n
must be nonnegative.
drop n xs
is the sequence xs
, deprived of its first n
elements.
If xs
has fewer than n
elements, then drop n xs
is empty.
n
must be nonnegative.
drop
is lazy: the first n+1
elements of the sequence xs
are demanded only when the first element of drop n xs
is demanded. For this reason, drop 1 xs
is not equivalent to tail xs
, which queries xs
immediately.
take_while p xs
is the longest prefix of the sequence xs
where every element x
satisfies p x
.
drop_while p xs
is the sequence xs
, deprived of the prefix take_while p xs
.
Provided the function eq
defines an equality on elements, group eq xs
is the sequence of the maximal runs of adjacent duplicate elements of the sequence xs
.
Every element of group eq xs
is a nonempty sequence of equal elements.
The concatenation concat (group eq xs)
is equal to xs
.
Consuming group eq xs
, and consuming the sequences that it contains, can cause xs
to be consumed more than once. Therefore, xs
must be persistent.
The sequence memoize xs
has the same elements as the sequence xs
.
Regardless of whether xs
is ephemeral or persistent, memoize xs
is persistent: even if it is queried several times, xs
is queried at most once.
The construction of the sequence memoize xs
internally relies on suspensions provided by the module Lazy
. These suspensions are not thread-safe. Therefore, the sequence memoize xs
must not be queried by multiple threads concurrently.
If xss
is a matrix (a sequence of rows), then transpose xss
is the sequence of the columns of the matrix xss
.
The rows of the matrix xss
are not required to have the same length.
The matrix xss
is not required to be finite (in either direction).
The matrix xss
must be persistent.
append xs ys
is the concatenation of the sequences xs
and ys
.
Its elements are the elements of xs
, followed by the elements of ys
.
If xss
is a sequence of sequences, then concat xss
is its concatenation.
If xss
is the sequence xs0; xs1; ...
then concat xss
is the sequence xs0 @ xs1 @ ...
.
concat_map f xs
is equivalent to concat (map f xs)
.
concat_map
is an alias for flat_map
.
zip xs ys
is the sequence of pairs (x, y)
drawn synchronously from the sequences xs
and ys
.
If the sequences xs
and ys
have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
zip xs ys
is equivalent to map2 (fun a b -> (a, b)) xs ys
.
map2 f xs ys
is the sequence of the elements f x y
, where the pairs (x, y)
are drawn synchronously from the sequences xs
and ys
.
If the sequences xs
and ys
have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
map2 f xs ys
is equivalent to map (fun (x, y) -> f x y) (zip xs ys)
.
interleave xs ys
is the sequence that begins with the first element of xs
, continues with the first element of ys
, and so on.
When one of the sequences xs
and ys
is exhausted, interleave xs ys
continues with the rest of the other sequence.
If the sequences xs
and ys
are sorted according to the total preorder cmp
, then sorted_merge cmp xs ys
is the sorted sequence obtained by merging the sequences xs
and ys
.
For more details on comparison functions, see Array.sort
.
product xs ys
is the Cartesian product of the sequences xs
and ys
.
For every element x
of xs
and for every element y
of ys
, the pair (x, y)
appears once as an element of product xs ys
.
The order in which the pairs appear is unspecified.
The sequences xs
and ys
are not required to be finite.
The sequences xs
and ys
must be persistent.
The sequence map_product f xs ys
is the image through f
of the Cartesian product of the sequences xs
and ys
.
For every element x
of xs
and for every element y
of ys
, the element f x y
appears once as an element of map_product f xs ys
.
The order in which these elements appear is unspecified.
The sequences xs
and ys
are not required to be finite.
The sequences xs
and ys
must be persistent.
map_product f xs ys
is equivalent to map (fun (x, y) -> f x y) (product xs ys)
.
unzip
transforms a sequence of pairs into a pair of sequences.
unzip xs
is equivalent to (map fst xs, map snd xs)
.
Querying either of the sequences returned by unzip xs
causes xs
to be queried. Therefore, querying both of them causes xs
to be queried twice. Thus, xs
must be persistent and cheap. If that is not the case, use unzip (memoize xs)
.
partition_map f xs
returns a pair of sequences (ys, zs)
, where:
ys
is the sequence of the elements y
such that f x = Left y
, where x
ranges over xs
;zs
is the sequence of the elements z
such that f x = Right z
, where x
ranges over xs
.partition_map f xs
is equivalent to a pair of filter_map Either.find_left (map f xs)
and filter_map Either.find_right (map f xs)
.
Querying either of the sequences returned by partition_map f xs
causes xs
to be queried. Therefore, querying both of them causes xs
to be queried twice. Thus, xs
must be persistent and cheap. If that is not the case, use partition_map f (memoize xs)
.
partition p xs
returns a pair of the subsequence of the elements of xs
that satisfy p
and the subsequence of the elements of xs
that do not satisfy p
.
partition p xs
is equivalent to filter p xs, filter (fun x -> not (p x)) xs
.
Consuming both of the sequences returned by partition p xs
causes xs
to be consumed twice and causes the function f
to be applied twice to each element of the list. Therefore, f
should be pure and cheap. Furthermore, xs
should be persistent and cheap. If that is not the case, use partition p (memoize xs)
.
val of_dispenser : (unit -> 'a option) -> 'a t
of_dispenser it
is the sequence of the elements produced by the dispenser it
. It is an ephemeral sequence: it can be consumed at most once. If a persistent sequence is needed, use memoize (of_dispenser it)
.
val ints : int -> int t
ints i
is the infinite sequence of the integers beginning at i
and counting up.
The sequence once xs
has the same elements as the sequence xs
.
Regardless of whether xs
is ephemeral or persistent, once xs
is an ephemeral sequence: it can be queried at most once. If it (or a suffix of it) is queried more than once, then the exception Forced_twice
is raised. This can be useful, while debugging or testing, to ensure that a sequence is consumed at most once.
This exception is raised when a sequence returned by once
(or a suffix of it) is queried more than once.
val to_dispenser : 'a t -> unit -> 'a option
to_dispenser xs
is a fresh dispenser on the sequence xs
.
This dispenser has mutable internal state, which is not protected by a lock; so, it must not be used by several threads concurrently.
StdLabels.List
include sig ... end
Compare the lengths of two lists. compare_lengths l1 l2
is equivalent to compare (length l1) (length l2)
, except that the computation stops after reaching the end of the shortest list.
Compare the length of a list to an integer. compare_length_with l len
is equivalent to compare (length l) len
, except that the computation stops after at most len
iterations on the list.
is_empty l
is true if and only if l
has no elements. It is equivalent to compare_length_with l 0 = 0
.
Return the n
-th element of the given list. The first element (head of the list) is at position 0.
Return the n
-th element of the given list. The first element (head of the list) is at position 0. Return None
if the list is too short.
init ~len ~f
is [f 0; f 1; ...; f (len-1)]
, evaluated left to right.
append l0 l1
appends l1
to l0
. Same function as the infix operator @
.
rev_append l1 l2
reverses l1
and concatenates it with l2
. This is equivalent to (
rev
l1) @ l2
.
Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument + length of the longest sub-list).
Same as concat
. Not tail-recursive (length of the argument + length of the longest sub-list).
equal eq [a1; ...; an] [b1; ..; bm]
holds when the two input lists have the same length, and for each pair of elements ai
, bi
at the same position we have eq ai bi
.
Note: the eq
function may be called even if the lists have different length. If you know your equality function is costly, you may want to check compare_lengths
first.
compare cmp [a1; ...; an] [b1; ...; bm]
performs a lexicographic comparison of the two input lists, using the same 'a -> 'a -> int
interface as Stdlib.compare
:
a1 :: l1
is smaller than a2 :: l2
(negative result) if a1
is smaller than a2
, or if they are equal (0 result) and l1
is smaller than l2
[]
is strictly smaller than non-empty listsNote: the cmp
function will be called even if the lists have different lengths.
iter ~f [a1; ...; an]
applies function f
in turn to [a1; ...; an]
. It is equivalent to f a1; f a2; ...; f an
.
Same as iter
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
map ~f [a1; ...; an]
applies function f
to a1, ..., an
, and builds the list [f a1; ...; f an]
with the results returned by f
.
Same as map
, but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
filter_map ~f l
applies f
to every element of l
, filters out the None
elements and returns the list of the arguments of the Some
elements.
fold_left_map
is a combination of fold_left
and map
that threads an accumulator through calls to f
.
fold_left ~f ~init [b1; ...; bn]
is f (... (f (f init b1) b2) ...) bn
.
fold_right ~f [a1; ...; an] ~init
is f a1 (f a2 (... (f an init) ...))
. Not tail-recursive.
iter2 ~f [a1; ...; an] [b1; ...; bn]
calls in turn f a1 b1; ...; f an bn
.
map2 ~f [a1; ...; an] [b1; ...; bn]
is [f a1 b1; ...; f an bn]
.
fold_left2 ~f ~init [a1; ...; an] [b1; ...; bn]
is f (... (f (f init a1 b1) a2 b2) ...) an bn
.
fold_right2 ~f [a1; ...; an] [b1; ...; bn] ~init
is f a1 b1 (f a2 b2 (... (f an bn init) ...))
.
for_all ~f [a1; ...; an]
checks if all elements of the list satisfy the predicate f
. That is, it returns (f a1) && (f a2) && ... && (f an)
for a non-empty list and true
if the list is empty.
exists ~f [a1; ...; an]
checks if at least one element of the list satisfies the predicate f
. That is, it returns (f a1) || (f a2) || ... || (f an)
for a non-empty list and false
if the list is empty.
Same as for_all
, but for a two-argument predicate.
Same as exists
, but for a two-argument predicate.
mem a ~set
is true if and only if a
is equal to an element of set
.
find ~f l
returns the first element of the list l
that satisfies the predicate f
.
find ~f l
returns the first element of the list l
that satisfies the predicate f
. Returns None
if there is no value that satisfies f
in the list l
.
find_index ~f xs
returns Some i
, where i
is the index of the first element of the list xs
that satisfies f x
, if there is such an element.
It returns None
if there is no such element.
find_map ~f l
applies f
to the elements of l
in order, and returns the first result of the form Some v
, or None
if none exist.
Same as find_map
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
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 is preserved.
find_all
is another name for filter
.
Same as filter
, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
partition ~f l
returns a pair of lists (l1, l2)
, where l1
is the list of all the elements of l
that satisfy the predicate f
, and l2
is the list of all the elements of l
that do not satisfy f
. The order of the elements in the input list is preserved.
partition_map f l
returns a pair of lists (l1, l2)
such that, for each element x
of the input list l
:
f x
is Left y1
, then y1
is in l1
, andf x
is Right y2
, then y2
is in l2
.The output elements are included in l1
and l2
in the same relative order as the corresponding input elements in l
.
In particular, partition_map (fun x -> if f x then Left x else Right x) l
is equivalent to partition f l
.
assoc a l
returns the value associated with key a
in the list of pairs l
. That is, assoc a [ ...; (a,b); ...] = b
if (a,b)
is the leftmost binding of a
in list l
.
assoc_opt a l
returns the value associated with key a
in the list of pairs l
. That is, assoc_opt a [ ...; (a,b); ...] = Some b
if (a,b)
is the leftmost binding of a
in list l
. Returns None
if there is no value associated with a
in the list l
.
Same as assoc
, but simply return true
if a binding exists, and false
if no bindings exist for the given key.
remove_assoc a l
returns the list of pairs l
without the first pair with key a
, if any. Not tail-recursive.
Transform a list of pairs into a pair of lists: split [(a1,b1); ...; (an,bn)]
is ([a1; ...; an], [b1; ...; bn])
. Not tail-recursive.
Transform a pair of lists into a list of pairs: combine [a1; ...; an] [b1; ...; bn]
is [(a1,b1); ...; (an,bn)]
.
Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, Stdlib.compare
is a suitable comparison function. The resulting list is sorted in increasing order. sort
is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space.
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
, but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order).
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
Same as sort
or stable_sort
, whichever is faster on typical input.
Same as sort
, but also remove duplicates.
Merge two lists: Assuming that l1
and l2
are sorted according to the comparison function cmp
, merge ~cmp l1 l2
will return a sorted list containing all the elements of l1
and l2
. If several elements compare equal, the elements of l1
will be before the elements of l2
. Not tail-recursive (sum of the lengths of the arguments).
Same as mem
, but uses physical equality instead of structural equality to compare list elements.
Same as assoc
, but uses physical equality instead of structural equality to compare keys.
Same as assoc_opt
, but uses physical equality instead of structural equality to compare keys.
Same as mem_assoc
, but uses physical equality instead of structural equality to compare keys.
Same as remove_assoc
, but uses physical equality instead of structural equality to compare keys. Not tail-recursive.
StdLabels.String
include sig ... end
make n c
is a string of length n
with each index holding the character c
.
init n ~f
is a string of length n
with index i
holding the character f i
(called in increasing index order).
get s i
is the character at index i
in s
. This is the same as writing s.[i]
.
concat ~sep ss
concatenates the list of strings ss
, inserting the separator string sep
between each.
compare s0 s1
sorts s0
and s1
in lexicographical order. compare
behaves like Stdlib.compare
on strings but may be more efficient.
starts_with
~prefix s
is true
if and only if s
starts with prefix
.
ends_with
~suffix s
is true
if and only if s
ends with suffix
.
contains_from s start c
is true
if and only if c
appears in s
after position start
.
rcontains_from s stop c
is true
if and only if c
appears in s
before position stop+1
.
contains s c
is String.contains_from
s 0 c
.
sub s ~pos ~len
is a string of length len
, containing the substring of s
that starts at position pos
and has length len
.
split_on_char ~sep s
is the list of all (possibly empty) substrings of s
that are delimited by the character sep
.
The function's result is specified by the following invariants:
sep
as a separator returns a string equal to the input (concat (make 1 sep)
+ (split_on_char sep s) = s
).sep
character.map f s
is the string resulting from applying f
to all the characters of s
in increasing order.
mapi ~f s
is like map
but the index of the character is also passed to f
.
fold_left f x s
computes f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]
, where n
is the length of the string s
.
fold_right f s x
computes f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))
, where n
is the length of the string s
.
for_all p s
checks if all characters in s
satisfy the predicate p
.
exists p s
checks if at least one character of s
satisfies the predicate p
.
trim s
is s
without leading and trailing whitespace. Whitespace characters are: ' '
, '\x0C'
(form feed), '\n'
, '\r'
, and '\t'
.
escaped s
is s
with special characters represented by escape sequences, following the lexical conventions of OCaml.
All characters outside the US-ASCII printable range [0x20;0x7E] are escaped, as well as backslash (0x2F) and double-quote (0x22).
The function Scanf.unescaped
is a left inverse of escaped
, i.e. Scanf.unescaped (escaped s) = s
for any string s
(unless escaped s
fails).
uppercase_ascii s
is s
with all lowercase letters translated to uppercase, using the US-ASCII character set.
lowercase_ascii s
is s
with all uppercase letters translated to lowercase, using the US-ASCII character set.
capitalize_ascii s
is s
with the first character set to uppercase, using the US-ASCII character set.
uncapitalize_ascii s
is s
with the first character set to lowercase, using the US-ASCII character set.
iter ~f s
applies function f
in turn to all the characters of s
. It is equivalent to f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()
.
iteri
is like iter
, but the function is also given the corresponding character index.
index_from s i c
is the index of the first occurrence of c
in s
after position i
.
index_from_opt s i c
is the index of the first occurrence of c
in s
after position i
(if any).
rindex_from s i c
is the index of the last occurrence of c
in s
before position i+1
.
rindex_from_opt s i c
is the index of the last occurrence of c
in s
before position i+1
(if any).
index s c
is String.index_from
s 0 c
.
index_opt s c
is String.index_from_opt
s 0 c
.
rindex s c
is String.rindex_from
s (length s - 1) c
.
rindex_opt s c
is String.rindex_from_opt
s (length s - 1) c
.
val to_seq : t -> char Stdlib.Seq.t
to_seq s
is a sequence made of the string's characters in increasing order. In "unsafe-string"
mode, modifications of the string during iteration will be reflected in the sequence.
val to_seqi : t -> (int * char) Stdlib.Seq.t
to_seqi s
is like to_seq
but also tuples the corresponding index.
val of_seq : char Stdlib.Seq.t -> t
of_seq s
is a string made of the sequence's characters.
val get_utf_8_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_8_uchar b i
decodes an UTF-8 character at index i
in b
.
val is_valid_utf_8 : t -> bool
is_valid_utf_8 b
is true
if and only if b
contains valid UTF-8 data.
val get_utf_16be_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16be_uchar b i
decodes an UTF-16BE character at index i
in b
.
val is_valid_utf_16be : t -> bool
is_valid_utf_16be b
is true
if and only if b
contains valid UTF-16BE data.
val get_utf_16le_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16le_uchar b i
decodes an UTF-16LE character at index i
in b
.
val is_valid_utf_16le : t -> bool
is_valid_utf_16le b
is true
if and only if b
contains valid UTF-16LE data.
get_uint8 b i
is b
's unsigned 8-bit integer starting at character index i
.
get_int8 b i
is b
's signed 8-bit integer starting at character index i
.
get_uint16_ne b i
is b
's native-endian unsigned 16-bit integer starting at character index i
.
get_uint16_be b i
is b
's big-endian unsigned 16-bit integer starting at character index i
.
get_uint16_le b i
is b
's little-endian unsigned 16-bit integer starting at character index i
.
get_int16_ne b i
is b
's native-endian signed 16-bit integer starting at character index i
.
get_int16_be b i
is b
's big-endian signed 16-bit integer starting at character index i
.
get_int16_le b i
is b
's little-endian signed 16-bit integer starting at character index i
.
get_int32_ne b i
is b
's native-endian 32-bit integer starting at character index i
.
val hash : t -> int
An unseeded hash function for strings, with the same output value as Hashtbl.hash
. This function allows this module to be passed as argument to the functor Hashtbl.Make
.
val seeded_hash : int -> t -> int
A seeded hash function for strings, with the same output value as Hashtbl.seeded_hash
. This function allows this module to be passed as argument to the functor Hashtbl.MakeSeeded
.
get_int32_be b i
is b
's big-endian 32-bit integer starting at character index i
.
get_int32_le b i
is b
's little-endian 32-bit integer starting at character index i
.
get_int64_ne b i
is b
's native-endian 64-bit integer starting at character index i
.
get_int64_be b i
is b
's big-endian 64-bit integer starting at character index i
.
get_int64_le b i
is b
's little-endian 64-bit integer starting at character index i
.
Return a new string that contains the same bytes as the given byte sequence.
Return a new byte sequence that contains the same bytes as the given string.
Stdlib_alerting.StdLabels
module String : StringLabels_alerting
module List : ListLabels_alerting
Stdlib_alerting.String
include sig ... end
make n c
is a string of length n
with each index holding the character c
.
init n f
is a string of length n
with index i
holding the character f i
(called in increasing index order).
get s i
is the character at index i
in s
. This is the same as writing s.[i]
.
concat sep ss
concatenates the list of strings ss
, inserting the separator string sep
between each.
compare s0 s1
sorts s0
and s1
in lexicographical order. compare
behaves like Stdlib.compare
on strings but may be more efficient.
starts_with
~prefix s
is true
if and only if s
starts with prefix
.
ends_with
~suffix s
is true
if and only if s
ends with suffix
.
contains_from s start c
is true
if and only if c
appears in s
after position start
.
rcontains_from s stop c
is true
if and only if c
appears in s
before position stop+1
.
contains s c
is String.contains_from
s 0 c
.
sub s pos len
is a string of length len
, containing the substring of s
that starts at position pos
and has length len
.
split_on_char sep s
is the list of all (possibly empty) substrings of s
that are delimited by the character sep
.
The function's result is specified by the following invariants:
sep
as a separator returns a string equal to the input (concat (make 1 sep)
+ (split_on_char sep s) = s
).sep
character.map f s
is the string resulting from applying f
to all the characters of s
in increasing order.
mapi f s
is like map
but the index of the character is also passed to f
.
fold_left f x s
computes f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]
, where n
is the length of the string s
.
fold_right f s x
computes f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))
, where n
is the length of the string s
.
for_all p s
checks if all characters in s
satisfy the predicate p
.
exists p s
checks if at least one character of s
satisfies the predicate p
.
trim s
is s
without leading and trailing whitespace. Whitespace characters are: ' '
, '\x0C'
(form feed), '\n'
, '\r'
, and '\t'
.
escaped s
is s
with special characters represented by escape sequences, following the lexical conventions of OCaml.
All characters outside the US-ASCII printable range [0x20;0x7E] are escaped, as well as backslash (0x2F) and double-quote (0x22).
The function Scanf.unescaped
is a left inverse of escaped
, i.e. Scanf.unescaped (escaped s) = s
for any string s
(unless escaped s
fails).
uppercase_ascii s
is s
with all lowercase letters translated to uppercase, using the US-ASCII character set.
lowercase_ascii s
is s
with all uppercase letters translated to lowercase, using the US-ASCII character set.
capitalize_ascii s
is s
with the first character set to uppercase, using the US-ASCII character set.
uncapitalize_ascii s
is s
with the first character set to lowercase, using the US-ASCII character set.
iter f s
applies function f
in turn to all the characters of s
. It is equivalent to f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()
.
iteri
is like iter
, but the function is also given the corresponding character index.
index_from s i c
is the index of the first occurrence of c
in s
after position i
.
index_from_opt s i c
is the index of the first occurrence of c
in s
after position i
(if any).
rindex_from s i c
is the index of the last occurrence of c
in s
before position i+1
.
rindex_from_opt s i c
is the index of the last occurrence of c
in s
before position i+1
(if any).
index s c
is String.index_from
s 0 c
.
index_opt s c
is String.index_from_opt
s 0 c
.
rindex s c
is String.rindex_from
s (length s - 1) c
.
rindex_opt s c
is String.rindex_from_opt
s (length s - 1) c
.
val to_seq : t -> char Stdlib.Seq.t
to_seq s
is a sequence made of the string's characters in increasing order. In "unsafe-string"
mode, modifications of the string during iteration will be reflected in the sequence.
val to_seqi : t -> (int * char) Stdlib.Seq.t
to_seqi s
is like to_seq
but also tuples the corresponding index.
val of_seq : char Stdlib.Seq.t -> t
of_seq s
is a string made of the sequence's characters.
val get_utf_8_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_8_uchar b i
decodes an UTF-8 character at index i
in b
.
val is_valid_utf_8 : t -> bool
is_valid_utf_8 b
is true
if and only if b
contains valid UTF-8 data.
val get_utf_16be_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16be_uchar b i
decodes an UTF-16BE character at index i
in b
.
val is_valid_utf_16be : t -> bool
is_valid_utf_16be b
is true
if and only if b
contains valid UTF-16BE data.
val get_utf_16le_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16le_uchar b i
decodes an UTF-16LE character at index i
in b
.
val is_valid_utf_16le : t -> bool
is_valid_utf_16le b
is true
if and only if b
contains valid UTF-16LE data.
get_uint8 b i
is b
's unsigned 8-bit integer starting at character index i
.
get_int8 b i
is b
's signed 8-bit integer starting at character index i
.
get_uint16_ne b i
is b
's native-endian unsigned 16-bit integer starting at character index i
.
get_uint16_be b i
is b
's big-endian unsigned 16-bit integer starting at character index i
.
get_uint16_le b i
is b
's little-endian unsigned 16-bit integer starting at character index i
.
get_int16_ne b i
is b
's native-endian signed 16-bit integer starting at character index i
.
get_int16_be b i
is b
's big-endian signed 16-bit integer starting at character index i
.
get_int16_le b i
is b
's little-endian signed 16-bit integer starting at character index i
.
get_int32_ne b i
is b
's native-endian 32-bit integer starting at character index i
.
val hash : t -> int
An unseeded hash function for strings, with the same output value as Hashtbl.hash
. This function allows this module to be passed as argument to the functor Hashtbl.Make
.
val seeded_hash : int -> t -> int
A seeded hash function for strings, with the same output value as Hashtbl.seeded_hash
. This function allows this module to be passed as argument to the functor Hashtbl.MakeSeeded
.
get_int32_be b i
is b
's big-endian 32-bit integer starting at character index i
.
get_int32_le b i
is b
's little-endian 32-bit integer starting at character index i
.
get_int64_ne b i
is b
's native-endian 64-bit integer starting at character index i
.
get_int64_be b i
is b
's big-endian 64-bit integer starting at character index i
.
get_int64_le b i
is b
's little-endian 64-bit integer starting at character index i
.
Return a new string that contains the same bytes as the given byte sequence.
Return a new byte sequence that contains the same bytes as the given string.
Stdlib_alerting.StringLabels
include sig ... end
make n c
is a string of length n
with each index holding the character c
.
init n ~f
is a string of length n
with index i
holding the character f i
(called in increasing index order).
get s i
is the character at index i
in s
. This is the same as writing s.[i]
.
concat ~sep ss
concatenates the list of strings ss
, inserting the separator string sep
between each.
compare s0 s1
sorts s0
and s1
in lexicographical order. compare
behaves like Stdlib.compare
on strings but may be more efficient.
starts_with
~prefix s
is true
if and only if s
starts with prefix
.
ends_with
~suffix s
is true
if and only if s
ends with suffix
.
contains_from s start c
is true
if and only if c
appears in s
after position start
.
rcontains_from s stop c
is true
if and only if c
appears in s
before position stop+1
.
contains s c
is String.contains_from
s 0 c
.
sub s ~pos ~len
is a string of length len
, containing the substring of s
that starts at position pos
and has length len
.
split_on_char ~sep s
is the list of all (possibly empty) substrings of s
that are delimited by the character sep
.
The function's result is specified by the following invariants:
sep
as a separator returns a string equal to the input (concat (make 1 sep)
+ (split_on_char sep s) = s
).sep
character.map f s
is the string resulting from applying f
to all the characters of s
in increasing order.
mapi ~f s
is like map
but the index of the character is also passed to f
.
fold_left f x s
computes f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]
, where n
is the length of the string s
.
fold_right f s x
computes f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))
, where n
is the length of the string s
.
for_all p s
checks if all characters in s
satisfy the predicate p
.
exists p s
checks if at least one character of s
satisfies the predicate p
.
trim s
is s
without leading and trailing whitespace. Whitespace characters are: ' '
, '\x0C'
(form feed), '\n'
, '\r'
, and '\t'
.
escaped s
is s
with special characters represented by escape sequences, following the lexical conventions of OCaml.
All characters outside the US-ASCII printable range [0x20;0x7E] are escaped, as well as backslash (0x2F) and double-quote (0x22).
The function Scanf.unescaped
is a left inverse of escaped
, i.e. Scanf.unescaped (escaped s) = s
for any string s
(unless escaped s
fails).
uppercase_ascii s
is s
with all lowercase letters translated to uppercase, using the US-ASCII character set.
lowercase_ascii s
is s
with all uppercase letters translated to lowercase, using the US-ASCII character set.
capitalize_ascii s
is s
with the first character set to uppercase, using the US-ASCII character set.
uncapitalize_ascii s
is s
with the first character set to lowercase, using the US-ASCII character set.
iter ~f s
applies function f
in turn to all the characters of s
. It is equivalent to f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()
.
iteri
is like iter
, but the function is also given the corresponding character index.
index_from s i c
is the index of the first occurrence of c
in s
after position i
.
index_from_opt s i c
is the index of the first occurrence of c
in s
after position i
(if any).
rindex_from s i c
is the index of the last occurrence of c
in s
before position i+1
.
rindex_from_opt s i c
is the index of the last occurrence of c
in s
before position i+1
(if any).
index s c
is String.index_from
s 0 c
.
index_opt s c
is String.index_from_opt
s 0 c
.
rindex s c
is String.rindex_from
s (length s - 1) c
.
rindex_opt s c
is String.rindex_from_opt
s (length s - 1) c
.
val to_seq : t -> char Stdlib.Seq.t
to_seq s
is a sequence made of the string's characters in increasing order. In "unsafe-string"
mode, modifications of the string during iteration will be reflected in the sequence.
val to_seqi : t -> (int * char) Stdlib.Seq.t
to_seqi s
is like to_seq
but also tuples the corresponding index.
val of_seq : char Stdlib.Seq.t -> t
of_seq s
is a string made of the sequence's characters.
val get_utf_8_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_8_uchar b i
decodes an UTF-8 character at index i
in b
.
val is_valid_utf_8 : t -> bool
is_valid_utf_8 b
is true
if and only if b
contains valid UTF-8 data.
val get_utf_16be_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16be_uchar b i
decodes an UTF-16BE character at index i
in b
.
val is_valid_utf_16be : t -> bool
is_valid_utf_16be b
is true
if and only if b
contains valid UTF-16BE data.
val get_utf_16le_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16le_uchar b i
decodes an UTF-16LE character at index i
in b
.
val is_valid_utf_16le : t -> bool
is_valid_utf_16le b
is true
if and only if b
contains valid UTF-16LE data.
get_uint8 b i
is b
's unsigned 8-bit integer starting at character index i
.
get_int8 b i
is b
's signed 8-bit integer starting at character index i
.
get_uint16_ne b i
is b
's native-endian unsigned 16-bit integer starting at character index i
.
get_uint16_be b i
is b
's big-endian unsigned 16-bit integer starting at character index i
.
get_uint16_le b i
is b
's little-endian unsigned 16-bit integer starting at character index i
.
get_int16_ne b i
is b
's native-endian signed 16-bit integer starting at character index i
.
get_int16_be b i
is b
's big-endian signed 16-bit integer starting at character index i
.
get_int16_le b i
is b
's little-endian signed 16-bit integer starting at character index i
.
get_int32_ne b i
is b
's native-endian 32-bit integer starting at character index i
.
val hash : t -> int
An unseeded hash function for strings, with the same output value as Hashtbl.hash
. This function allows this module to be passed as argument to the functor Hashtbl.Make
.
val seeded_hash : int -> t -> int
A seeded hash function for strings, with the same output value as Hashtbl.seeded_hash
. This function allows this module to be passed as argument to the functor Hashtbl.MakeSeeded
.
get_int32_be b i
is b
's big-endian 32-bit integer starting at character index i
.
get_int32_le b i
is b
's little-endian 32-bit integer starting at character index i
.
get_int64_ne b i
is b
's native-endian 64-bit integer starting at character index i
.
get_int64_be b i
is b
's big-endian 64-bit integer starting at character index i
.
get_int64_le b i
is b
's little-endian 64-bit integer starting at character index i
.
Return a new string that contains the same bytes as the given byte sequence.
Return a new byte sequence that contains the same bytes as the given string.
Stdlib_alerting.Uchar
include sig ... end
The type for Unicode characters.
A value of this type represents a Unicode scalar value which is an integer in the ranges 0x0000
...0xD7FF
or 0xE000
...0x10FFFF
.
val min : t
min
is U+0000.
val max : t
max
is U+10FFFF.
val bom : t
bom
is U+FEFF, the byte order mark (BOM) character.
val rep : t
rep
is U+FFFD, the replacement character.
is_valid n
is true
if and only if n
is a Unicode scalar value (i.e. in the ranges 0x0000
...0xD7FF
or 0xE000
...0x10FFFF
).
val of_int : int -> t
of_int i
is i
as a Unicode character.
val to_int : t -> int
to_int u
is u
as an integer.
val is_char : t -> bool
is_char u
is true
if and only if u
is a latin1 OCaml character.
val of_char : char -> t
of_char c
is c
as a Unicode character.
val to_char : t -> char
to_char u
is u
as an OCaml latin1 character.
val hash : t -> int
hash u
associates a non-negative integer to u
.
The type for UTF decode results. Values of this type represent the result of a Unicode Transformation Format decoding attempt.
val utf_decode_is_valid : utf_decode -> bool
utf_decode_is_valid d
is true
if and only if d
holds a valid decode.
val utf_decode_uchar : utf_decode -> t
utf_decode_uchar d
is the Unicode character decoded by d
if utf_decode_is_valid d
is true
and Uchar.rep
otherwise.
val utf_decode_length : utf_decode -> int
utf_decode_length d
is the number of elements from the source that were consumed by the decode d
. This is always strictly positive and smaller or equal to 4
. The kind of source elements depends on the actual decoder; for the decoders of the standard library this function always returns a length in bytes.
val utf_decode : int -> t -> utf_decode
utf_decode n u
is a valid UTF decode for u
that consumed n
elements from the source for decoding. n
must be positive and smaller or equal to 4
(this is not checked by the module).
val utf_decode_invalid : int -> utf_decode
utf_decode_invalid n
is an invalid UTF decode that consumed n
elements from the source to error. n
must be positive and smaller or equal to 4
(this is not checked by the module). The resulting decode has rep
as the decoded Unicode character.
val utf_8_byte_length : t -> int
utf_8_byte_length u
is the number of bytes needed to encode u
in UTF-8.
val utf_16_byte_length : t -> int
utf_16_byte_length u
is the number of bytes needed to encode u
in UTF-16.
Stdlib_alerts.Stdlib_alerting
Derived from Stdlib
, but with items that can be restricted annotated with alerts.
Things that can be restricted are marked with an ⚠️ Alert. Not everything marked here is disabled by default though. See Stdlib_alerts
for the defaults.
raise
primitives and standard exceptionsinclude sig ... end
The Exit
exception is not raised by any library function. It is provided for use in your programs.
Exception raised when none of the cases of a pattern-matching apply. The arguments are the location of the match keyword in the source code (file name, line number, column number).
Exception raised when an assertion fails. The arguments are the location of the assert keyword in the source code (file name, line number, column number).
Exception raised by library functions to signal that the given arguments do not make sense. The string gives some information to the programmer. As a general rule, this exception should not be caught, it denotes a programming error and the code should be modified not to trigger it.
Exception raised by library functions to signal that they are undefined on the given arguments. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Failure _ instead).
Exception raised by the garbage collector when there is insufficient memory to complete the computation. (Not reliable for allocations on the minor heap.)
Exception raised by the bytecode interpreter when the evaluation stack reaches its maximal size. This often indicates infinite or excessively deep recursion in the user's program.
Before 4.10, it was not fully implemented by the native-code compiler.
Exception raised by the input/output functions to report an operating system error. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Sys_error _ instead).
Exception raised by input functions to signal that the end of file has been reached.
Exception raised by integer division and remainder operations when their second argument is zero.
A special case of Sys_error raised when no I/O is possible on a non-blocking I/O channel.
Not including the impure (==)
and (!=)
.
include sig ... end
e1 = e2
tests for structural equality of e1
and e2
. Mutable structures (e.g. references and arrays) are equal if and only if their current contents are structurally equal, even if the two mutable objects are not the same physical object. Equality between functional values raises Invalid_argument
. Equality between cyclic data structures may not terminate. Left-associative operator, see Ocaml_operators
for more information.
Negation of Stdlib.(=)
. Left-associative operator, see Ocaml_operators
for more information.
See Stdlib.(>=)
. Left-associative operator, see Ocaml_operators
for more information.
See Stdlib.(>=)
. Left-associative operator, see Ocaml_operators
for more information.
See Stdlib.(>=)
. Left-associative operator, see Ocaml_operators
for more information.
Structural ordering functions. These functions coincide with the usual orderings over integers, characters, strings, byte sequences and floating-point numbers, and extend them to a total ordering over all types. The ordering is compatible with ( = )
. As in the case of ( = )
, mutable structures are compared by contents. Comparison between functional values raises Invalid_argument
. Comparison between cyclic structures may not terminate. Left-associative operator, see Ocaml_operators
for more information.
compare x y
returns 0
if x
is equal to y
, a negative integer if x
is less than y
, and a positive integer if x
is greater than y
. The ordering implemented by compare
is compatible with the comparison predicates =
, <
and >
defined above, with one difference on the treatment of the float value Stdlib.nan
. Namely, the comparison predicates treat nan
as different from any other float value, including itself; while compare
treats nan
as equal to itself and less than any other float value. This treatment of nan
ensures that compare
defines a total ordering relation.
compare
applied to functional values may raise Invalid_argument
. compare
applied to cyclic structures may not terminate.
The compare
function can be used as the comparison function required by the Set.Make
and Map.Make
functors, as well as the List.sort
and Array.sort
functions.
Return the smaller of the two arguments. The result is unspecified if one of the arguments contains the float value nan
.
The impure (==)
and (!=)
include sig ... end
e1 == e2
tests for physical equality of e1
and e2
. On mutable types such as references, arrays, byte sequences, records with mutable fields and objects with mutable instance variables, e1 == e2
is true if and only if physical modification of e1
also affects e2
. On non-mutable types, the behavior of ( == )
is implementation-dependent; however, it is guaranteed that e1 == e2
implies compare e1 e2 = 0
. Left-associative operator, see Ocaml_operators
for more information.
include sig ... end
The boolean 'and'. Evaluation is sequential, left-to-right: in e1 && e2
, e1
is evaluated first, and if it returns false
, e2
is not evaluated at all. Right-associative operator, see Ocaml_operators
for more information.
These are safe in the sense that referential transparency is preserved, if two uses of a macro at separate locations are considered separate occurrences.
include sig ... end
__LOC__
returns the location at which this expression appears in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d".
__LINE__
returns the line number at which this expression appears in the file currently being parsed by the compiler.
__POS__
returns a tuple (file,lnum,cnum,enum)
, corresponding to the location at which this expression appears in the file currently being parsed by the compiler. file
is the current filename, lnum
the line number, cnum
the character position in the line and enum
the last character position in the line.
__FUNCTION__
returns the name of the current function or method, including any enclosing modules or classes.
__LOC_OF__ expr
returns a pair (loc, expr)
where loc
is the location of expr
in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d".
__LINE_OF__ expr
returns a pair (line, expr)
, where line
is the line number at which the expression expr
appears in the file currently being parsed by the compiler.
__POS_OF__ expr
returns a pair (loc,expr)
, where loc
is a tuple (file,lnum,cnum,enum)
corresponding to the location at which the expression expr
appears in the file currently being parsed by the compiler. file
is the current filename, lnum
the line number, cnum
the character position in the line and enum
the last character position in the line.
include sig ... end
Reverse-application operator: x |> f |> g
is exactly equivalent to g (f (x))
. Left-associative operator, see Ocaml_operators
for more information.
include sig ... end
Unary negation. You can also write - e
instead of ~- e
. Unary operator, see Ocaml_operators
for more information.
Unary addition. You can also write + e
instead of ~+ e
. Unary operator, see Ocaml_operators
for more information.
Integer addition. Left-associative operator, see Ocaml_operators
for more information.
Integer subtraction. Left-associative operator, , see Ocaml_operators
for more information.
Integer multiplication. Left-associative operator, see Ocaml_operators
for more information.
Integer division. Integer division rounds the real quotient of its arguments towards zero. More precisely, if x >= 0
and y > 0
, x / y
is the greatest integer less than or equal to the real quotient of x
by y
. Moreover, (- x) / y = x / (- y) = - (x / y)
. Left-associative operator, see Ocaml_operators
for more information.
Integer remainder. If y
is not zero, the result of x mod y
satisfies the following properties: x = (x / y) * y + x mod y
and abs(x mod y) <= abs(y) - 1
. If y = 0
, x mod y
raises Division_by_zero
. Note that x mod y
is negative only if x < 0
. Left-associative operator, see Ocaml_operators
for more information.
abs x
is the absolute value of x
. On min_int
this is min_int
itself and thus remains negative.
Bitwise logical and. Left-associative operator, see Ocaml_operators
for more information.
Bitwise logical or. Left-associative operator, see Ocaml_operators
for more information.
Bitwise logical exclusive or. Left-associative operator, see Ocaml_operators
for more information.
n lsl m
shifts n
to the left by m
bits. The result is unspecified if m < 0
or m > Sys.int_size
. Right-associative operator, see Ocaml_operators
for more information.
n lsr m
shifts n
to the right by m
bits. This is a logical shift: zeroes are inserted regardless of the sign of n
. The result is unspecified if m < 0
or m > Sys.int_size
. Right-associative operator, see Ocaml_operators
for more information.
n asr m
shifts n
to the right by m
bits. This is an arithmetic shift: the sign bit of n
is replicated. The result is unspecified if m < 0
or m > Sys.int_size
. Right-associative operator, see Ocaml_operators
for more information.
include sig ... end
Unary negation. You can also write -. e
instead of ~-. e
. Unary operator, see Ocaml_operators
for more information.
Unary addition. You can also write +. e
instead of ~+. e
. Unary operator, see Ocaml_operators
for more information.
Floating-point addition. Left-associative operator, see Ocaml_operators
for more information.
Floating-point subtraction. Left-associative operator, see Ocaml_operators
for more information.
Floating-point multiplication. Left-associative operator, see Ocaml_operators
for more information.
Floating-point division. Left-associative operator, see Ocaml_operators
for more information.
Exponentiation. Right-associative operator, see Ocaml_operators
for more information.
expm1 x
computes exp x -. 1.0
, giving numerically-accurate results even if x
is close to 0.0
.
Arc cosine. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and is between 0.0
and pi
.
Arc sine. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and is between -pi/2
and pi/2
.
atan2 y x
returns the arc tangent of y /. x
. The signs of x
and y
are used to determine the quadrant of the result. Result is in radians and is between -pi
and pi
.
hypot x y
returns sqrt(x *. x + y *. y)
, that is, the length of the hypotenuse of a right-angled triangle with sides of length x
and y
, or, equivalently, the distance of the point (x,y)
to origin. If one of x
or y
is infinite, returns infinity
even if the other is nan
.
Hyperbolic arc cosine. The argument must fall within the range [1.0, inf]
. Result is in radians and is between 0.0
and inf
.
log1p x
computes log(1.0 +. x)
(natural logarithm), giving numerically-accurate results even if x
is close to 0.0
.
Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians.
Hyperbolic arc tangent. The argument must fall within the range [-1.0, 1.0]
. Result is in radians and ranges over the entire real line.
Round above to an integer value. ceil f
returns the least integer value greater than or equal to f
. The result is returned as a float.
Round below to an integer value. floor f
returns the greatest integer value less than or equal to f
. The result is returned as a float.
copysign x y
returns a float whose absolute value is that of x
and whose sign is that of y
. If x
is nan
, returns nan
. If y
is nan
, returns either x
or -. x
, but it is not specified which.
mod_float a b
returns the remainder of a
with respect to b
. The returned value is a -. n *. b
, where n
is the quotient a /. b
rounded towards zero to an integer.
frexp f
returns the pair of the significant and the exponent of f
. When f
is zero, the significant x
and the exponent n
of f
are equal to zero. When f
is non-zero, they are defined by f = x *. 2 ** n
and 0.5 <= x < 1.0
.
Truncate the given floating-point number to an integer. The result is unspecified if the argument is nan
or falls outside the range of representable integers.
A special floating-point value denoting the result of an undefined operation such as 0.0 /. 0.0
. Stands for 'not a number'. Any floating-point operation with nan
as argument returns nan
as result, unless otherwise specified in IEEE 754 standard. As for floating-point comparisons, =
, <
, <=
, >
and >=
return false
and <>
returns true
if one or both of their arguments is nan
.
nan
is a quiet NaN since 5.1; it was a signaling NaN before.
The difference between 1.0
and the smallest exactly representable floating-point number greater than 1.0
.
The five classes of floating-point numbers, as determined by the Stdlib.classify_float
function.
val classify_float : float -> fpclass
Return the class of the given floating-point number: normal, subnormal, zero, infinite, or not a number.
More in Stdlib.String
More in Stdlib.Char
include sig ... end
include sig ... end
Return the string representation of a boolean. As the returned values may be shared, the user should not modify them directly.
Convert the given string to a boolean.
Return None
if the string is not "true"
or "false"
.
Same as Stdlib.bool_of_string_opt
, but raise Invalid_argument "bool_of_string"
instead of returning None
.
Convert the given string to an integer. The string is read in decimal (by default, or if the string begins with 0u
), in hexadecimal (if it begins with 0x
or 0X
), in octal (if it begins with 0o
or 0O
), or in binary (if it begins with 0b
or 0B
).
The 0u
prefix reads the input as an unsigned integer in the range [0, 2*max_int+1]
. If the input exceeds max_int
it is converted to the signed integer min_int + input - max_int - 1
.
The _
(underscore) character can appear anywhere in the string and is ignored.
Return None
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 int
.
Same as Stdlib.int_of_string_opt
, but raise Failure "int_of_string"
instead of returning None
.
Return a string representation of a floating-point number.
This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see Printf
.
Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by 0x
or 0X
).
The format of decimal floating-point numbers is [-] dd.ddd (e|E) [+|-] dd
, where d
stands for a decimal digit.
The format of hexadecimal floating-point numbers is [-] 0(x|X) hh.hhh (p|P) [+|-] dd
, where h
stands for an hexadecimal digit and d
for a decimal digit.
In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional.
The _
(underscore) character can appear anywhere in the string and is ignored.
Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon.
Return None
if the given string is not a valid representation of a float.
More in Stdlib.List
include sig ... end
l0 @ l1
appends l1
to l0
. Same function as List.append
. Right-associative operator, see Ocaml_operators
for more information.
This is regular, unmocked, IO.
include sig ... end
val stdin : in_channel
The standard input for the process.
val stdout : out_channel
The standard output for the process.
val stderr : out_channel
The standard error output for the process.
Print a floating-point number, in decimal, on standard output.
The conversion of the number to a string uses string_of_float
and can involve a loss of precision.
Print a string, followed by a newline character, on standard output and flush standard output.
Print a newline character on standard output, and flush standard output. This can be used to simulate line buffering of standard output.
Print a floating-point number, in decimal, on standard error.
The conversion of the number to a string uses string_of_float
and can involve a loss of precision.
Print a string, followed by a newline character on standard error and flush standard error.
Print a newline character on standard error, and flush standard error.
Flush standard output, then read characters from standard input until a newline character is encountered.
Return the string of all characters read, without the newline character at the end.
Flush standard output, then read one line from standard input and convert it to an integer.
Return None
if the line read is not a valid representation of an integer.
Same as Stdlib.read_int_opt
, but raise Failure "int_of_string"
instead of returning None
.
Flush standard output, then read one line from standard input and convert it to a floating-point number.
Return None
if the line read is not a valid representation of a floating-point number.
Same as Stdlib.read_float_opt
, but raise Failure "float_of_string"
instead of returning None
.
type open_flag =
| Open_rdonly
open for reading.
*)| Open_wronly
open for writing.
*)| Open_append
open for appending: always write at end of file.
*)| Open_creat
create the file if it does not exist.
*)| Open_trunc
empty the file if it already exists.
*)| Open_excl
fail if Open_creat and the file already exists.
*)| Open_binary
open in binary mode (no conversion).
*)| Open_text
open in text mode (may perform conversions).
*)| Open_nonblock
open in non-blocking mode.
*)Opening modes for Stdlib.open_out_gen
and Stdlib.open_in_gen
.
val open_out : string -> out_channel
Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists.
val open_out_bin : string -> out_channel
Same as Stdlib.open_out
, but the file is opened in binary mode, so that no translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like Stdlib.open_out
.
val open_out_gen : open_flag list -> int -> string -> out_channel
open_out_gen mode perm filename
opens the named file for writing, as described above. The extra argument mode
specifies the opening mode. The extra argument perm
specifies the file permissions, in case the file must be created. Stdlib.open_out
and Stdlib.open_out_bin
are special cases of this function.
val flush : out_channel -> unit
Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time.
val output_char : out_channel -> char -> unit
Write the character on the given output channel.
val output_string : out_channel -> string -> unit
Write the string on the given output channel.
val output_bytes : out_channel -> bytes -> unit
Write the byte sequence on the given output channel.
val output : out_channel -> bytes -> int -> int -> unit
output oc buf pos len
writes len
characters from byte sequence buf
, starting at offset pos
, to the given output channel oc
.
val output_substring : out_channel -> string -> int -> int -> unit
Same as output
but take a string as argument instead of a byte sequence.
val output_byte : out_channel -> int -> unit
Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256.
val output_binary_int : out_channel -> int -> unit
Write one integer in binary format (4 bytes, big-endian) on the given output channel. The given integer is taken modulo 232. The only reliable way to read it back is through the Stdlib.input_binary_int
function. The format is compatible across all machines for a given version of OCaml.
val output_value : out_channel -> 'a -> unit
Write the representation of a structured value of any type to a channel. Circularities and sharing inside the value are detected and preserved. The object can be read back, by the function Stdlib.input_value
. See the description of module Marshal
for more information. Stdlib.output_value
is equivalent to Marshal.to_channel
with an empty list of flags.
val seek_out : out_channel -> int -> unit
seek_out chan pos
sets the current writing position to pos
for channel chan
. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified.
val pos_out : out_channel -> int
Return the current writing position for the given channel. Does not work on channels opened with the Open_append
flag (returns unspecified results). For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with pos_out
, then going back to this position using seek_out
will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode.
val out_channel_length : out_channel -> int
Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless.
val close_out : out_channel -> unit
Close the given channel, flushing all buffered write operations. Output functions raise a Sys_error
exception when they are applied to a closed output channel, except close_out
and flush
, which do nothing when applied to an already closed channel. Note that close_out
may raise Sys_error
if the operating system signals an error when flushing or closing.
val close_out_noerr : out_channel -> unit
Same as close_out
, but ignore all errors.
val set_binary_mode_out : out_channel -> bool -> unit
set_binary_mode_out oc true
sets the channel oc
to binary mode: no translations take place during output. set_binary_mode_out oc false
sets the channel oc
to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from \n
to \r\n
. This function has no effect under operating systems that do not distinguish between text mode and binary mode.
val open_in : string -> in_channel
Open the named file for reading, and return a new input channel on that file, positioned at the beginning of the file.
val open_in_bin : string -> in_channel
Same as Stdlib.open_in
, but the file is opened in binary mode, so that no translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like Stdlib.open_in
.
val open_in_gen : open_flag list -> int -> string -> in_channel
open_in_gen mode perm filename
opens the named file for reading, as described above. The extra arguments mode
and perm
specify the opening mode and file permissions. Stdlib.open_in
and Stdlib.open_in_bin
are special cases of this function.
val input_char : in_channel -> char
Read one character from the given input channel.
val input_line : in_channel -> string
Read characters from the given input channel, until a newline character is encountered. Return the string of all characters read, without the newline character at the end.
val input : in_channel -> bytes -> int -> int -> int
input ic buf pos len
reads up to len
characters from the given channel ic
, storing them in byte sequence buf
, starting at character number pos
. It returns the actual number of characters read, between 0 and len
(inclusive). A return value of 0 means that the end of file was reached. A return value between 0 and len
exclusive means that not all requested len
characters were read, either because no more characters were available at that time, or because the implementation found it convenient to do a partial read; input
must be called again to read the remaining characters, if desired. (See also Stdlib.really_input
for reading exactly len
characters.) Exception Invalid_argument "input"
is raised if pos
and len
do not designate a valid range of buf
.
val really_input : in_channel -> bytes -> int -> int -> unit
really_input ic buf pos len
reads len
characters from channel ic
, storing them in byte sequence buf
, starting at character number pos
.
val really_input_string : in_channel -> int -> string
really_input_string ic len
reads len
characters from channel ic
and returns them in a new string.
val input_byte : in_channel -> int
Same as Stdlib.input_char
, but return the 8-bit integer representing the character.
val input_binary_int : in_channel -> int
Read an integer encoded in binary format (4 bytes, big-endian) from the given input channel. See Stdlib.output_binary_int
.
val input_value : in_channel -> 'a
Read the representation of a structured value, as produced by Stdlib.output_value
, and return the corresponding value. This function is identical to Marshal.from_channel
; see the description of module Marshal
for more information, in particular concerning the lack of type safety.
val seek_in : in_channel -> int -> unit
seek_in chan pos
sets the current reading position to pos
for channel chan
. This works only for regular files. On files of other kinds, the behavior is unspecified.
val pos_in : in_channel -> int
Return the current reading position for the given channel. For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with pos_in
, then going back to this position using seek_in
will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode.
val in_channel_length : in_channel -> int
Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode.
val close_in : in_channel -> unit
Close the given channel. Input functions raise a Sys_error
exception when they are applied to a closed input channel, except close_in
, which does nothing when applied to an already closed channel.
val close_in_noerr : in_channel -> unit
Same as close_in
, but ignore all errors.
val set_binary_mode_in : in_channel -> bool -> unit
set_binary_mode_in ic true
sets the channel ic
to binary mode: no translations take place during input. set_binary_mode_out ic false
sets the channel ic
to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from \r\n
to \n
. This function has no effect under operating systems that do not distinguish between text mode and binary mode.
module LargeFile : sig ... end
Operations on large files. This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type int64
) instead of regular integers (type int
), these alternate functions allow operating on files whose sizes are greater than max_int
.
include sig ... end
The type of references (mutable indirection cells) containing a value of type 'a
.
val ref : 'a -> 'a ref
Return a fresh reference containing the given value.
val (!) : 'a ref -> 'a
!r
returns the current contents of reference r
. Equivalent to fun r -> r.contents
. Unary operator, see Ocaml_operators
for more information.
val (:=) : 'a ref -> 'a -> unit
r := a
stores the value of a
in reference r
. Equivalent to fun r v -> r.contents <- v
. Right-associative operator, see Ocaml_operators
for more information.
val incr : int ref -> unit
Increment the integer contained in the given reference. Equivalent to fun r -> r := succ !r
.
val decr : int ref -> unit
Decrement the integer contained in the given reference. Equivalent to fun r -> r := pred !r
.
More in Stdlib.Result
More in Stdlib.Scanf
, Stdlib.Printf
, and Stdlib.Format
include sig ... end
type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6
type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4
format_of_string s
returns a format string read from the string literal s
. Note: format_of_string
can not convert a string argument that is not a literal. If you need this functionality, use the more general Scanf.format_from_string
function.
val (^^) :
+ ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
+ ('f, 'b, 'c, 'e, 'g, 'h) format6 ->
+ ('a, 'b, 'c, 'd, 'g, 'h) format6
f1 ^^ f2
catenates format strings f1
and f2
. The result is a format string that behaves as the concatenation of format strings f1
and f2
: in case of formatted output, it accepts arguments from f1
, then arguments from f2
; in case of formatted input, it returns results from f1
, then results from f2
. Right-associative operator, see Ocaml_operators
for more information.
include sig ... end
Terminate the process, returning the given status code to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. All open output channels are flushed with flush_all
. The callbacks registered with Domain.at_exit
are called followed by those registered with Stdlib.at_exit
.
An implicit exit 0
is performed each time a program terminates normally. An implicit exit 2
is performed if the program terminates early because of an uncaught exception.
Register the given function to be called at program termination time. The functions registered with at_exit
will be called when the program does any of the following:
Stdlib.exit
caml_shutdown
. The functions are called in 'last in, first out' order: the function most recently added with at_exit
is called first.include sig ... end
module Char : Char_alerting
module Digest : Digest_alerting
module Filename : Filename_alerting
module Float : Float_alerting
module Hashtbl : Hashtbl_alerting
module List : List_alerting
module ListLabels : ListLabels_alerting
module MoreLabels : MoreLabels_alerting
module Printexc : Printexc_alerting
module Printf : Printf_alerting
module Scanf : Scanf_alerting
module Seq : Seq_alerting
module StdLabels : StdLabels_alerting
module String : String_alerting
module StringLabels : StringLabels_alerting
module Uchar : Uchar_alerting
Modules containing advanced features for interacting with the runtime system.
include sig ... end
Stdlib_alerts.StringLabels_alerting
include sig ... end
make n c
is a string of length n
with each index holding the character c
.
init n ~f
is a string of length n
with index i
holding the character f i
(called in increasing index order).
get s i
is the character at index i
in s
. This is the same as writing s.[i]
.
concat ~sep ss
concatenates the list of strings ss
, inserting the separator string sep
between each.
compare s0 s1
sorts s0
and s1
in lexicographical order. compare
behaves like Stdlib.compare
on strings but may be more efficient.
starts_with
~prefix s
is true
if and only if s
starts with prefix
.
ends_with
~suffix s
is true
if and only if s
ends with suffix
.
contains_from s start c
is true
if and only if c
appears in s
after position start
.
rcontains_from s stop c
is true
if and only if c
appears in s
before position stop+1
.
sub s ~pos ~len
is a string of length len
, containing the substring of s
that starts at position pos
and has length len
.
split_on_char ~sep s
is the list of all (possibly empty) substrings of s
that are delimited by the character sep
.
The function's result is specified by the following invariants:
sep
as a separator returns a string equal to the input (concat (make 1 sep)
+ (split_on_char sep s) = s
).sep
character.map f s
is the string resulting from applying f
to all the characters of s
in increasing order.
mapi ~f s
is like map
but the index of the character is also passed to f
.
fold_left f x s
computes f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]
, where n
is the length of the string s
.
fold_right f s x
computes f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))
, where n
is the length of the string s
.
for_all p s
checks if all characters in s
satisfy the predicate p
.
exists p s
checks if at least one character of s
satisfies the predicate p
.
trim s
is s
without leading and trailing whitespace. Whitespace characters are: ' '
, '\x0C'
(form feed), '\n'
, '\r'
, and '\t'
.
escaped s
is s
with special characters represented by escape sequences, following the lexical conventions of OCaml.
All characters outside the US-ASCII printable range [0x20;0x7E] are escaped, as well as backslash (0x2F) and double-quote (0x22).
The function Scanf.unescaped
is a left inverse of escaped
, i.e. Scanf.unescaped (escaped s) = s
for any string s
(unless escaped s
fails).
uppercase_ascii s
is s
with all lowercase letters translated to uppercase, using the US-ASCII character set.
lowercase_ascii s
is s
with all uppercase letters translated to lowercase, using the US-ASCII character set.
capitalize_ascii s
is s
with the first character set to uppercase, using the US-ASCII character set.
uncapitalize_ascii s
is s
with the first character set to lowercase, using the US-ASCII character set.
iter ~f s
applies function f
in turn to all the characters of s
. It is equivalent to f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()
.
iteri
is like iter
, but the function is also given the corresponding character index.
index_from s i c
is the index of the first occurrence of c
in s
after position i
.
index_from_opt s i c
is the index of the first occurrence of c
in s
after position i
(if any).
rindex_from s i c
is the index of the last occurrence of c
in s
before position i+1
.
rindex_from_opt s i c
is the index of the last occurrence of c
in s
before position i+1
(if any).
rindex_opt s c
is String.rindex_from_opt
s (length s - 1) c
.
val to_seq : t -> char Stdlib.Seq.t
to_seq s
is a sequence made of the string's characters in increasing order. In "unsafe-string"
mode, modifications of the string during iteration will be reflected in the sequence.
val to_seqi : t -> (int * char) Stdlib.Seq.t
to_seqi s
is like to_seq
but also tuples the corresponding index.
val of_seq : char Stdlib.Seq.t -> t
of_seq s
is a string made of the sequence's characters.
val get_utf_8_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_8_uchar b i
decodes an UTF-8 character at index i
in b
.
val is_valid_utf_8 : t -> bool
is_valid_utf_8 b
is true
if and only if b
contains valid UTF-8 data.
val get_utf_16be_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16be_uchar b i
decodes an UTF-16BE character at index i
in b
.
val is_valid_utf_16be : t -> bool
is_valid_utf_16be b
is true
if and only if b
contains valid UTF-16BE data.
val get_utf_16le_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16le_uchar b i
decodes an UTF-16LE character at index i
in b
.
val is_valid_utf_16le : t -> bool
is_valid_utf_16le b
is true
if and only if b
contains valid UTF-16LE data.
get_uint8 b i
is b
's unsigned 8-bit integer starting at character index i
.
get_int8 b i
is b
's signed 8-bit integer starting at character index i
.
get_uint16_ne b i
is b
's native-endian unsigned 16-bit integer starting at character index i
.
get_uint16_be b i
is b
's big-endian unsigned 16-bit integer starting at character index i
.
get_uint16_le b i
is b
's little-endian unsigned 16-bit integer starting at character index i
.
get_int16_ne b i
is b
's native-endian signed 16-bit integer starting at character index i
.
get_int16_be b i
is b
's big-endian signed 16-bit integer starting at character index i
.
get_int16_le b i
is b
's little-endian signed 16-bit integer starting at character index i
.
get_int32_ne b i
is b
's native-endian 32-bit integer starting at character index i
.
val hash : t -> int
An unseeded hash function for strings, with the same output value as Hashtbl.hash
. This function allows this module to be passed as argument to the functor Hashtbl.Make
.
val seeded_hash : int -> t -> int
A seeded hash function for strings, with the same output value as Hashtbl.seeded_hash
. This function allows this module to be passed as argument to the functor Hashtbl.MakeSeeded
.
get_int32_be b i
is b
's big-endian 32-bit integer starting at character index i
.
get_int32_le b i
is b
's little-endian 32-bit integer starting at character index i
.
get_int64_ne b i
is b
's native-endian 64-bit integer starting at character index i
.
get_int64_be b i
is b
's big-endian 64-bit integer starting at character index i
.
get_int64_le b i
is b
's little-endian 64-bit integer starting at character index i
.
Return a new string that contains the same bytes as the given byte sequence.
Return a new byte sequence that contains the same bytes as the given string.
Stdlib_alerts.String_alerting
include sig ... end
make n c
is a string of length n
with each index holding the character c
.
init n f
is a string of length n
with index i
holding the character f i
(called in increasing index order).
get s i
is the character at index i
in s
. This is the same as writing s.[i]
.
concat sep ss
concatenates the list of strings ss
, inserting the separator string sep
between each.
compare s0 s1
sorts s0
and s1
in lexicographical order. compare
behaves like Stdlib.compare
on strings but may be more efficient.
starts_with
~prefix s
is true
if and only if s
starts with prefix
.
ends_with
~suffix s
is true
if and only if s
ends with suffix
.
contains_from s start c
is true
if and only if c
appears in s
after position start
.
rcontains_from s stop c
is true
if and only if c
appears in s
before position stop+1
.
sub s pos len
is a string of length len
, containing the substring of s
that starts at position pos
and has length len
.
split_on_char sep s
is the list of all (possibly empty) substrings of s
that are delimited by the character sep
.
The function's result is specified by the following invariants:
sep
as a separator returns a string equal to the input (concat (make 1 sep)
+ (split_on_char sep s) = s
).sep
character.map f s
is the string resulting from applying f
to all the characters of s
in increasing order.
mapi f s
is like map
but the index of the character is also passed to f
.
fold_left f x s
computes f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]
, where n
is the length of the string s
.
fold_right f s x
computes f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))
, where n
is the length of the string s
.
for_all p s
checks if all characters in s
satisfy the predicate p
.
exists p s
checks if at least one character of s
satisfies the predicate p
.
trim s
is s
without leading and trailing whitespace. Whitespace characters are: ' '
, '\x0C'
(form feed), '\n'
, '\r'
, and '\t'
.
escaped s
is s
with special characters represented by escape sequences, following the lexical conventions of OCaml.
All characters outside the US-ASCII printable range [0x20;0x7E] are escaped, as well as backslash (0x2F) and double-quote (0x22).
The function Scanf.unescaped
is a left inverse of escaped
, i.e. Scanf.unescaped (escaped s) = s
for any string s
(unless escaped s
fails).
uppercase_ascii s
is s
with all lowercase letters translated to uppercase, using the US-ASCII character set.
lowercase_ascii s
is s
with all uppercase letters translated to lowercase, using the US-ASCII character set.
capitalize_ascii s
is s
with the first character set to uppercase, using the US-ASCII character set.
uncapitalize_ascii s
is s
with the first character set to lowercase, using the US-ASCII character set.
iter f s
applies function f
in turn to all the characters of s
. It is equivalent to f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()
.
iteri
is like iter
, but the function is also given the corresponding character index.
index_from s i c
is the index of the first occurrence of c
in s
after position i
.
index_from_opt s i c
is the index of the first occurrence of c
in s
after position i
(if any).
rindex_from s i c
is the index of the last occurrence of c
in s
before position i+1
.
rindex_from_opt s i c
is the index of the last occurrence of c
in s
before position i+1
(if any).
rindex_opt s c
is String.rindex_from_opt
s (length s - 1) c
.
val to_seq : t -> char Stdlib.Seq.t
to_seq s
is a sequence made of the string's characters in increasing order. In "unsafe-string"
mode, modifications of the string during iteration will be reflected in the sequence.
val to_seqi : t -> (int * char) Stdlib.Seq.t
to_seqi s
is like to_seq
but also tuples the corresponding index.
val of_seq : char Stdlib.Seq.t -> t
of_seq s
is a string made of the sequence's characters.
val get_utf_8_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_8_uchar b i
decodes an UTF-8 character at index i
in b
.
val is_valid_utf_8 : t -> bool
is_valid_utf_8 b
is true
if and only if b
contains valid UTF-8 data.
val get_utf_16be_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16be_uchar b i
decodes an UTF-16BE character at index i
in b
.
val is_valid_utf_16be : t -> bool
is_valid_utf_16be b
is true
if and only if b
contains valid UTF-16BE data.
val get_utf_16le_uchar : t -> int -> Stdlib.Uchar.utf_decode
get_utf_16le_uchar b i
decodes an UTF-16LE character at index i
in b
.
val is_valid_utf_16le : t -> bool
is_valid_utf_16le b
is true
if and only if b
contains valid UTF-16LE data.
get_uint8 b i
is b
's unsigned 8-bit integer starting at character index i
.
get_int8 b i
is b
's signed 8-bit integer starting at character index i
.
get_uint16_ne b i
is b
's native-endian unsigned 16-bit integer starting at character index i
.
get_uint16_be b i
is b
's big-endian unsigned 16-bit integer starting at character index i
.
get_uint16_le b i
is b
's little-endian unsigned 16-bit integer starting at character index i
.
get_int16_ne b i
is b
's native-endian signed 16-bit integer starting at character index i
.
get_int16_be b i
is b
's big-endian signed 16-bit integer starting at character index i
.
get_int16_le b i
is b
's little-endian signed 16-bit integer starting at character index i
.
get_int32_ne b i
is b
's native-endian 32-bit integer starting at character index i
.
val hash : t -> int
An unseeded hash function for strings, with the same output value as Hashtbl.hash
. This function allows this module to be passed as argument to the functor Hashtbl.Make
.
val seeded_hash : int -> t -> int
A seeded hash function for strings, with the same output value as Hashtbl.seeded_hash
. This function allows this module to be passed as argument to the functor Hashtbl.MakeSeeded
.
get_int32_be b i
is b
's big-endian 32-bit integer starting at character index i
.
get_int32_le b i
is b
's little-endian 32-bit integer starting at character index i
.
get_int64_ne b i
is b
's native-endian 64-bit integer starting at character index i
.
get_int64_be b i
is b
's big-endian 64-bit integer starting at character index i
.
get_int64_le b i
is b
's little-endian 64-bit integer starting at character index i
.
Return a new string that contains the same bytes as the given byte sequence.
Return a new byte sequence that contains the same bytes as the given string.
Stdlib_alerts.Uchar_alerting
include sig ... end
The type for Unicode characters.
A value of this type represents a Unicode scalar value which is an integer in the ranges 0x0000
...0xD7FF
or 0xE000
...0x10FFFF
.
val min : t
min
is U+0000.
val max : t
max
is U+10FFFF.
val bom : t
bom
is U+FEFF, the byte order mark (BOM) character.
val rep : t
rep
is U+FFFD, the replacement character.
is_valid n
is true
if and only if n
is a Unicode scalar value (i.e. in the ranges 0x0000
...0xD7FF
or 0xE000
...0x10FFFF
).
val of_int : int -> t
of_int i
is i
as a Unicode character.
val to_int : t -> int
to_int u
is u
as an integer.
val is_char : t -> bool
is_char u
is true
if and only if u
is a latin1 OCaml character.
val of_char : char -> t
of_char c
is c
as a Unicode character.
val to_char : t -> char
to_char u
is u
as an OCaml latin1 character.
val hash : t -> int
hash u
associates a non-negative integer to u
.
The type for UTF decode results. Values of this type represent the result of a Unicode Transformation Format decoding attempt.
val utf_decode_is_valid : utf_decode -> bool
utf_decode_is_valid d
is true
if and only if d
holds a valid decode.
val utf_decode_uchar : utf_decode -> t
utf_decode_uchar d
is the Unicode character decoded by d
if utf_decode_is_valid d
is true
and Uchar.rep
otherwise.
val utf_decode_length : utf_decode -> int
utf_decode_length d
is the number of elements from the source that were consumed by the decode d
. This is always strictly positive and smaller or equal to 4
. The kind of source elements depends on the actual decoder; for the decoders of the standard library this function always returns a length in bytes.
val utf_decode : int -> t -> utf_decode
utf_decode n u
is a valid UTF decode for u
that consumed n
elements from the source for decoding. n
must be positive and smaller or equal to 4
(this is not checked by the module).
val utf_decode_invalid : int -> utf_decode
utf_decode_invalid n
is an invalid UTF decode that consumed n
elements from the source to error. n
must be positive and smaller or equal to 4
(this is not checked by the module). The resulting decode has rep
as the decoded Unicode character.
val utf_8_byte_length : t -> int
utf_8_byte_length u
is the number of bytes needed to encode u
in UTF-8.
val utf_16_byte_length : t -> int
utf_16_byte_length u
is the number of bytes needed to encode u
in UTF-16.
Stdlib_components.BooleanOperations
SAFE
Boolean operations
Stdlib_components.CharOperations
SAFE
Character operations -- more in module Char
Stdlib_components.Comparisons
SAFE
Polymorphic comparisons. Does not include the impure (==)
and (!=)
, which are in PhysicalComparisons
.
Stdlib_components.Composition
SAFE
Composition operators
Stdlib_components.Debugging
SAFE
Debugging macros
Stdlib_components.Exceptions
SAFE
raise
primitives and standard exceptions
Stdlib_components.Exit
UNSAFE
Functions exiting the program at_exit
, exit
Stdlib_components.FloatingPointOperations
SAFE
Floating-point operations
val classify_float : float -> fpclass
Stdlib_components.Formats
SAFE
Formats
IOOperations.LargeFile
val seek_out : out_channel -> int64 -> unit
val pos_out : out_channel -> int64
val out_channel_length : out_channel -> int64
val seek_in : in_channel -> int64 -> unit
val pos_in : in_channel -> int64
val in_channel_length : in_channel -> int64
Stdlib_components.IOOperations
UNSAFE
I/O operations. This is regular, unmocked, IO.
module LargeFile : sig ... end
Stdlib_components.IntegerOperations
SAFE
Integer operations
Stdlib_components.ListOperations
SAFE
List operations -- more in module List
Stdlib_components.PairOperations
SAFE
Pair operations
Stdlib_components.PhysicalComparisons
UNSAFE
The impure (==)
and (!=)
Stdlib_components.References
UNSAFE
References
val ref : 'a -> 'a ref
val (!) : 'a ref -> 'a
val (:=) : 'a ref -> 'a -> unit
val incr : int ref -> unit
val decr : int ref -> unit
Stdlib_components.Result
SAFE
Result type
SafeAliases.Float
As module type of Float
, but without Array
and ArrayLabels
.
SafeAliases.MoreLabels
SafeAliases.Printexc
SafeAliases.Printf
Scanf.Scanning
SafeAliases.Scanf
SafeAliases.Seq
As module type of Seq
, but without once
, Forced_twice
and to_dispenser
.
val is_empty : 'a t -> bool
val length : 'a t -> int
val iter : ('a -> unit) -> 'a t -> unit
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b t -> 'a
val iteri : (int -> 'a -> unit) -> 'a t -> unit
val fold_lefti : ('b -> int -> 'a -> 'b) -> 'b -> 'a t -> 'b
val for_all : ('a -> bool) -> 'a t -> bool
val exists : ('a -> bool) -> 'a t -> bool
val find : ('a -> bool) -> 'a t -> 'a option
val find_index : ('a -> bool) -> 'a t -> int option
val find_map : ('a -> 'b option) -> 'a t -> 'b option
val find_mapi : (int -> 'a -> 'b option) -> 'a t -> 'b option
val empty : 'a t
val return : 'a -> 'a t
val init : int -> (int -> 'a) -> 'a t
val unfold : ('b -> ('a * 'b) option) -> 'b -> 'a t
val repeat : 'a -> 'a t
val forever : (unit -> 'a) -> 'a t
val iterate : ('a -> 'a) -> 'a -> 'a t
val of_dispenser : (unit -> 'a option) -> 'a t
val ints : int -> int t
StdLabels.String
val to_seq : t -> char Stdlib.Seq.t
val to_seqi : t -> (int * char) Stdlib.Seq.t
val of_seq : char Stdlib.Seq.t -> t
val get_utf_8_uchar : t -> int -> Stdlib.Uchar.utf_decode
val is_valid_utf_8 : t -> bool
val get_utf_16be_uchar : t -> int -> Stdlib.Uchar.utf_decode
val is_valid_utf_16be : t -> bool
val get_utf_16le_uchar : t -> int -> Stdlib.Uchar.utf_decode
val is_valid_utf_16le : t -> bool
val hash : t -> int
val seeded_hash : int -> t -> int
SafeAliases.StdLabels
module String : sig ... end
SafeAliases.String
As module type of String
, but without some unsafe buffer-related functions.
val to_seq : t -> char Stdlib.Seq.t
val to_seqi : t -> (int * char) Stdlib.Seq.t
val of_seq : char Stdlib.Seq.t -> t
val get_utf_8_uchar : t -> int -> Stdlib.Uchar.utf_decode
val is_valid_utf_8 : t -> bool
val get_utf_16be_uchar : t -> int -> Stdlib.Uchar.utf_decode
val is_valid_utf_16be : t -> bool
val get_utf_16le_uchar : t -> int -> Stdlib.Uchar.utf_decode
val is_valid_utf_16le : t -> bool
val hash : t -> int
val seeded_hash : int -> t -> int
SafeAliases.StringLabels
val to_seq : t -> char Stdlib.Seq.t
val to_seqi : t -> (int * char) Stdlib.Seq.t
val of_seq : char Stdlib.Seq.t -> t
val get_utf_8_uchar : t -> int -> Stdlib.Uchar.utf_decode
val is_valid_utf_8 : t -> bool
val get_utf_16be_uchar : t -> int -> Stdlib.Uchar.utf_decode
val is_valid_utf_16be : t -> bool
val get_utf_16le_uchar : t -> int -> Stdlib.Uchar.utf_decode
val is_valid_utf_16le : t -> bool
val hash : t -> int
val seeded_hash : int -> t -> int
Stdlib_components.SafeAliases
SAFE
Safe modules from the standard library, and unsafe modules restricted to their safe functions.
module Float : sig ... end
As module type of Float
, but without Array
and ArrayLabels
.
module MoreLabels : sig ... end
module Printexc : sig ... end
module Printf : sig ... end
module Scanf : sig ... end
module Seq : sig ... end
As module type of Seq
, but without once
, Forced_twice
and to_dispenser
.
module StdLabels : sig ... end
module String : sig ... end
As module type of String
, but without some unsafe buffer-related functions.
module StringLabels : sig ... end
Stdlib_components.Stdlib_safe
SAFE
Everything safe from the standard library, including everything safe from sub-modules of Stdlib
.
include module type of struct include Exceptions end
include module type of struct include Composition end
include module type of struct include Debugging end
include module type of struct include Comparisons end
include module type of struct include BooleanOperations end
include module type of struct include IntegerOperations end
include module type of struct include FloatingPointOperations end
val classify_float : float -> fpclass
include module type of struct include StringOperations end
include module type of struct include CharOperations end
include module type of struct include UnitOperations end
include module type of struct include PairOperations end
include module type of struct include Result end
include module type of struct include StringConversion end
include module type of struct include ListOperations end
include module type of struct include Formats end
include module type of struct include SafeAliases end
module Bool = SafeAliases.Bool
module Char = SafeAliases.Char
module Complex = SafeAliases.Complex
module Either = SafeAliases.Either
module Float = SafeAliases.Float
module Fun = SafeAliases.Fun
module Int = SafeAliases.Int
module Int32 = SafeAliases.Int32
module Int64 = SafeAliases.Int64
module Lazy = SafeAliases.Lazy
module List = SafeAliases.List
module ListLabels = SafeAliases.ListLabels
module Map = SafeAliases.Map
module MoreLabels = SafeAliases.MoreLabels
module Nativeint = SafeAliases.Nativeint
module Option = SafeAliases.Option
module Printexc = SafeAliases.Printexc
module Printf = SafeAliases.Printf
module Result = SafeAliases.Result
module Scanf = SafeAliases.Scanf
module Seq = SafeAliases.Seq
module Set = SafeAliases.Set
module StdLabels = SafeAliases.StdLabels
module String = SafeAliases.String
module StringLabels = SafeAliases.StringLabels
module Uchar = SafeAliases.Uchar
module Unit = SafeAliases.Unit
Stdlib_components.StringConversion
SAFE
String conversion functions
Stdlib_components.StringOperations
SAFE
String operations -- more in Stdlib module String
Stdlib_components.UnitOperations
SAFE
Unit operations
Stdlib_components
Adapted from Stdlib
, with different components in different modules. In particular, a safe (pure) subset of OCaml features can be enabled by opening a subset of modules defined here.
module Exceptions : sig ... end
SAFE
raise
primitives and standard exceptions
module Composition : sig ... end
SAFE
Composition operators
module Debugging : sig ... end
SAFE
Debugging macros
module Comparisons : sig ... end
SAFE
Polymorphic comparisons. Does not include the impure (==)
and (!=)
, which are in PhysicalComparisons
.
module PhysicalComparisons : sig ... end
UNSAFE
The impure (==)
and (!=)
module BooleanOperations : sig ... end
SAFE
Boolean operations
module IntegerOperations : sig ... end
SAFE
Integer operations
module FloatingPointOperations : sig ... end
SAFE
Floating-point operations
module StringOperations : sig ... end
SAFE
String operations -- more in Stdlib module String
module CharOperations : sig ... end
SAFE
Character operations -- more in module Char
module UnitOperations : sig ... end
SAFE
Unit operations
module PairOperations : sig ... end
SAFE
Pair operations
module References : sig ... end
UNSAFE
References
module Result : sig ... end
SAFE
Result type
module StringConversion : sig ... end
SAFE
String conversion functions
module ListOperations : sig ... end
SAFE
List operations -- more in module List
module IOOperations : sig ... end
UNSAFE
I/O operations. This is regular, unmocked, IO.
module Formats : sig ... end
SAFE
Formats
module Exit : sig ... end
UNSAFE
Functions exiting the program at_exit
, exit
module SafeAliases : sig ... end
SAFE
Safe modules from the standard library, and unsafe modules restricted to their safe functions.
module Stdlib_safe : sig ... end
SAFE
Everything safe from the standard library, including everything safe from sub-modules of Stdlib
.
Test_lib.Grading
Provide a grade from a list of passed/failed tests and a grading scheme. Provides functionality to load tests from a JUnit XML file, tidy them up, and write the grading result back to a JUnit XML file.
val clamp : 'a clamp -> 'a -> 'a
clamp { min = x; max = y } z
constrains z
between x
and y
.
The result of grading a list of tests.
type testsuites = tests list
A group of testsuites (e.g. as extracted from a single JUnit XML file)
type grading_criterion =
| Passed of string
Did the given test pass?
*)| Failed of string
Did the given test fail?
*)| Not of grading_criterion
Negation (logical not).
*)| OneOf of grading_criterion list
Disjunction (logical or).
*)| AllOf of grading_criterion list
Conjunction (logical and).
*)| Constant of bool
Logical constant.
*)Logical formulas over test results.
Passed
and Failed
values may use wildcards:
a:b:c:
: matches anything of which it is a prefix, e.g. a:b:c:d:e
and a:b:c
.a:*:c
: matches any name in place of *
, e.g. a:mmm:c
.Both may be combined, e.g. a:*:c:
matches a:mm:c
and a:nn:c:d
. A name is considered to be any string that does not contain a :
. You are responsible for enforcing this convention yourself, it is not enforced by OUnit, for example.
For a Passed
value to evaluate to true, all tests matched by the wildcard need to pass, and for Failed
all need to fail. If you want the inverse behavior (at least one matched test needs to pass/fail), use Not
: Not (Failed "a:*:")
means "not all matched tests failed", which is logically equivalent to "at least one matched test passed". For this, you can use any_passed
and any_failed
.
It is an error to reference a test that does not exist. In the presence of wildcards, at least one test must match.
val implies : grading_criterion -> grading_criterion -> grading_criterion
Logical implication: implies a c = OneOf [Not a; c]
.
val any_passed : string -> grading_criterion
If a test case contains a wildcard, the behavior is to require that all tests that match pass (or that all tests fail). Use any_passed
(and any_failed
) to instead check that at least one test that matches passed (or at least one test that matches failed).
val any_failed : string -> grading_criterion
See any_passed
.
val evaluate_criterion : tests -> grading_criterion -> bool
Evaluate the logical formula over the assignment of test names to boolean pass/fail values.
val string_of_grading_criterion : ?indent:int -> grading_criterion -> string
type grading =
| Points of {
title : string;
points : int;
test_case : grading_criterion;
reason : tests -> grading_criterion -> string;
}
If the criterion test_case
evaluates to true
, assign a grade of points
, otherwise 0
.
| Group of {
title : string;
items : grading list;
max_points : int clamp option;
skip : string option;
If skip = Some r
, skip this group (assign a grade of 0
) with the reason r
.
}
A group of grading schemes. Assign the sum of grades from the sub-items, with an optional minimum/maximum number of points.
*)| Conditional of {
condition : grading_criterion;
message : string;
content : grading;
}
Assign a grade according to content
if the condition
evaluates to true
, otherwise 0
.
Grading scheme. Defines how to assign a numeric grade for a given set of test results.
val points :
+ ?skip:grading_criterion ->
+ ?reason:(tests -> grading_criterion -> string option) ->
+ ?penalty:bool ->
+ string ->
+ int ->
+ grading_criterion ->
+ grading
Wrapper for Points
. If reason
returns None
(the default), the displayed reason is decided by penalty
and points
:
"PASS"
/"FAIL"
if points
is non-negative, or penalty
is true
points
is negative, or penalty
is false
, then the grading criterion must evaluate to true
and the reason is "PENALTY"
, otherwise No_reason
is raised during evaluation.If reason
returns a value, that is used directly instead.
val assertion :
+ ?message:string ->
+ ?title:string ->
+ int ->
+ grading_criterion ->
+ grading
Wrapper for Points
, intended for debugging tests. If the given grading_criterion
does not evaluate to true, the message
is given as a reason along with a print-out of the criterion. Useful for verifying invariants between tests, e.g. that passing a more comprehensive test implies passing a test that tests a subset of functionality.
val points_p :
+ ?skip:grading_criterion ->
+ ?reason:(tests -> grading_criterion -> string option) ->
+ ?penalty:bool ->
+ string ->
+ int ->
+ string ->
+ grading
val points_f :
+ ?skip:grading_criterion ->
+ ?reason:(tests -> grading_criterion -> string option) ->
+ ?penalty:bool ->
+ string ->
+ int ->
+ string ->
+ grading
val points_c :
+ ?skip:grading_criterion ->
+ ?reason:(tests -> grading_criterion -> string option) ->
+ ?penalty:bool ->
+ string ->
+ int ->
+ bool ->
+ grading
val conditional : grading_criterion -> string -> grading -> grading
Wrappers for Conditional
, with the given condition or a constant.
Wrapper for Group
.
val evaluate_grading :
+ ?points_step_count:int ->
+ grading ->
+ tests ->
+ grading_result
Calculates a grade from the description of the grading and the list of passed/failed tests.
Functionality to read tests from JUnit XML files, clean up the files, and write evaluated grading to JUnit XML files.
val extract_cleanup_file : ?cleanup_to:string -> string -> testsuites
Extract the list of testsuites from a JUnit XML file. If cleanup_to
is given, write the result of tidying up the result back to disk. The paths may be identical, in which case the original file is overwritten.
val write_result : ?log_result:bool -> grading_result -> string -> unit
Write a grading result to file. If log_result
is true
(default), print a human-readable summary of grading results to standard error.
Helpers to perform the most common sequence of operations:
Steps 2 and 3 can be skipped if no grading scheme is used. These helpers always clean up in-place, i.e. overwrite the original XML file, which is the intended use.
val extract_cleanup_files : ?cleanup:bool -> string list -> testsuites
As extract_cleanup_file
but for a list of files. The list of testsuites from each file are concatenated to produce a single list of testsuites. If cleanup
is true
(default), then overwrite each file with the cleaned up result, otherwise don't clean up.
val process_files :
+ ?cleanup:bool ->
+ ?grade:(grading * int option * string) ->
+ ?log_result:bool ->
+ string list ->
+ unit
Combines extract_cleanup_files
, evaluate_grading
and write_result
.
Extracts grading and (optionally) cleans up in-place, as per extract_cleanup_files
. If grade
is Some (grading, points_step_count, path)
, then evaluate grading
as per evaluate_grading
with the given points_step_count
, and write the result to path
, as per write_result
.
val grading_options :
+ ?points_step_count:int ->
+ grading_to:string ->
+ grading ->
+ grading * int option * string
Helper to write the grade
argument to process_files
more nicely.
val prettify_results : ?grading:grading -> string -> unit
As per process_files
with a single path and ~cleanup:true
. If grading
is given, then that grading is passed through with a point_step_count
of 1
and the grading result written to grading.xml
in the same directory as the given file.
Test_lib.OUnit_util
Utilities for converting from QCheck to OUnit, and other OUnit-related functionality.
Convert a QCheck test to OUnit, overwriting the timeout. Automatically prevents excessive shrinking from timing out tests, by interrupting shrinking and showing the smallest value found so far once the timeout expires.
val message_of_visibility : visibility -> string
val hide_test : ?visibility:visibility -> OUnitTest.test -> OUnitTest.test
Hide a test according to the visibility
argument.
Join a test tree into a single test which only passes if all individual tests in the tree pass. Students will only be able to see the result of the first test that failed. Timeouts of individual tests are summed to produce a single timeout, which is applied to the combined test. This changes the timeout behavior of the tests. Intended for grouping tests, when grading is performed solely by assigning points to passed tests.
For more complex grouping, use the Grading
module.
Test_lib.QCheck_util
Helpers for QCheck-based tests.
Workaround to check if an exception is QCheck2.Test.User_fail
, since that exception is not exposed.
val assert_equal :
+ ?context:string ->
+ ?timeout:Mtime.span ->
+ eq:('a -> 'b -> 'c option) ->
+ printers:(('d -> string) * ('e -> string)) ->
+ (unit -> 'f) ->
+ (unit -> 'g) ->
+ ('h, string) Stdlib.result
Check if values are equal. Report a failure message as Error
if not. This monadic form is useful for properties that check nested functions, i.e. calling submission code contains functions that should once again be called.
Note: with timeout
, uses Common.Util.timeout_unix
, and thus nesting (within expected_f
or actual_f
) will not work as expected.
Turn an equality function into the form required for assert_equal
.
val assert_equal' :
+ ?eq:('a -> 'b -> unit option) ->
+ printer:('b -> string) ->
+ ?context:string ->
+ ?timeout:Mtime.span ->
+ (unit -> 'a) ->
+ (unit -> 'b) ->
+ (unit, string) Stdlib.result
Like assert_equal
, but when the types to compare are the same.
After performing one or more comparisons with assert_equal
, report a failure as a QCheck failure, or just return true
otherwise.
Test_lib.Test_util
Test_lib
Library of common functionality for writing tests.
module Grading : sig ... end
Provide a grade from a list of passed/failed tests and a grading scheme. Provides functionality to load tests from a JUnit XML file, tidy them up, and write the grading result back to a JUnit XML file.
module OUnit_util : sig ... end
Utilities for converting from QCheck to OUnit, and other OUnit-related functionality.
module QCheck_util : sig ... end
Helpers for QCheck-based tests.
module Test_util : sig ... end
Test_runner.Entry_point
Entry points for creating test driver executables from a task tree.
val term_of_runner : (Std_task.cfg -> 'a) -> 'b Cmdliner.Term.t
Testcase.error
if message
is Some _
, otherwise Testcase.pass
val task_runner :
+ ?build_report_path:string ->
+ ?report_success_details:bool ->
+ (Std_task.cfg -> (unit, unit) Task.tree) ->
+ Std_task.cfg ->
+ unit
Creates a task from the config, and runs it. Reports the result as a test case (in build_report_path
, default test-reports/build.xml
). If report_success_details
is false
(default), no detailed build report is shown when the build succeeds. Otherwise, the detailed report is always shown, which requires that the test case is marked as a failure.
val run_task_main :
+ ?build_report_path:string ->
+ ?report_success_details:bool ->
+ ?exit:(Cmdliner.Cmd.Exit.code -> 'a) ->
+ (Std_task.cfg -> (unit, unit) Task.tree) ->
+ 'b
Std_task.Messages
Test_runner.Std_task
Common tasks and tasks for the standard test setup.
Check if the directory contains a symlink. The directory itself may be a symlink.
module Messages : sig ... end
Task: remove the files which match condition
(default: .ml
files). Not recursive: only files in p
will be deleted, not in subdirectories.
val copy_files :
+ ?condition:FileUtil.test_file ->
+ cfg ->
+ string ->
+ string ->
+ ('a, unit) Task.tree
Task: copy the files which match condition
(default: .ml
files). Not recursive: only files in src0
will be copied, not in subdirectories.
val load_files :
+ cfg ->
+ ?condition:FileUtil.test_file ->
+ string ->
+ string ->
+ ('a, unit) Task.tree
Composition of remove_files
and load_files
.
val checker :
+ cfg ->
+ ?prohibited:Ast_check.Feature.Set.t ->
+ ?limit:int ->
+ ?check1:FileUtil.test_file ->
+ ?check:FileUtil.test_file ->
+ string ->
+ ('a, unit) Task.tree
Run the AST-checker as a task.
val subprocess_run :
+ ?timeout:Common.P_run.timeout_description ->
+ ?args:string list ->
+ ?env:(string * string) list ->
+ string ->
+ ('a, Common.P_run.result) Task.tree
Run a process as a task
val subprocess_result :
+ ?hide_stdout:bool ->
+ ?hide_stderr:bool ->
+ ?command_line:string list ->
+ ?error_message:string ->
+ ?check_status:bool ->
+ ?dump_output:bool ->
+ unit ->
+ (Common.P_run.result, Common.P_run.result) Task.tree
Handle the result of a subprocess task.
type subprocess_options = {
timeout : Common.P_run.timeout_description option;
hide_stdout : bool;
hide_stderr : bool;
error_message : string option;
check_status : bool;
dump_output : bool;
}
val subprocess_options :
+ ?timeout:Common.P_run.timeout_description ->
+ ?hide_stdout:bool ->
+ ?hide_stderr:bool ->
+ ?error_message:string ->
+ ?check_status:bool ->
+ ?dump_output:bool ->
+ unit ->
+ subprocess_options
val subprocess :
+ cfg ->
+ ?options:subprocess_options ->
+ ?args:string list ->
+ ?env:(string * string) list ->
+ string ->
+ ('a, Common.P_run.result) Task.tree
val dune :
+ cfg ->
+ ?options:subprocess_options ->
+ root:string ->
+ ?args:string list ->
+ ?env:(string * string) list ->
+ string ->
+ ('a, Common.P_run.result) Task.tree
val timeout_for : cfg -> [< `Build | `Probe | `Test ] -> Mtime.span
These are high-level tasks built upon the primitives defined above. They work with the recommended layout of tests, submission and sample solution. However, the low-level tasks defined above can also be used as needed.
val std_build1 :
+ cfg ->
+ ?submission:bool ->
+ ?env:(string * string) list ->
+ string ->
+ ('a, unit) Task.tree
Build something in the tests/
directory with dune. If submission
is false
(default), error output is hidden.
val std_exec1 :
+ cfg ->
+ ?phase:[< `Build | `Probe | `Test ] ->
+ ?args:string list ->
+ ?env:(string * string) list ->
+ string ->
+ ('a, unit) Task.tree
Run something in the tests/
directory with dune exec
.
This task passes the --no-build
flag to dune. As such:
std_build1
).If phase
is given, sets a timeout.
val std_exec_test :
+ cfg ->
+ ?env:(string * string) list ->
+ ?shards:int option ->
+ output_junit_file:string ->
+ string ->
+ (unit, unit) Task.tree
Run a test executable in the standard setup. See the note about building first in std_exec1
. Assumes the test executable is configured to exit immediately if no command line arguments are passed. We use this to check that the top level code of the submission does not contain any long-running code. If it does, there's no point in running the tests, since the significantly longer test timeout will just kill them. We don't want to prohibit top-level code entirely, since it would prevent things like let impl0 = impl 0
.
Thus, first runs the given executable without any arguments, then runs it a second time, with the given output_junit_file
(interpreted relative to the test-reports/
directory) as the output JUnit file.
As std_exec_test
, fixed to test/test.exe
with output to test-reports/results.xml
.
Run an executable that processes the test results in the standard setup. Executes test/process_results.exe
. See the note about building first in std_exec1
.
The given file names are taken relative to the test-reports/
directory and passed to the executable.
val std_process_results :
+ ?grading:bool ->
+ ?output_junit_files:string list ->
+ cfg ->
+ ('a, unit) Task.tree
As std_exec_process_results
, but: if grading
is true
, the first argument to the executable is test-reports/grading.xml
. In any case, the remaining output_junit_files
(taken relative to the test-reports/
directory) follow, which defaults to ["results.xml"]
.
val probe_result_of_prun_result :
+ name:string ->
+ Common.P_run.result ->
+ probe_result
val defines_of_probe_result : probe_result -> string list
val load_probe_items :
+ cfg ->
+ defs:string ->
+ ('a, (string * Parsetree.structure) list) Task.tree
parse the probe items from the given path
val run_probe :
+ cfg ->
+ root:string ->
+ data_dir:string ->
+ name:string ->
+ ('a, probe_result) Task.tree
unlike the other tasks, data_dir
needs to be relative to root
here
val handle_probe_results :
+ cfg ->
+ args_file:string ->
+ (probe_result list, unit) Task.tree
Test_runner.Task
Set up, build, and run tests using first-class tasks.
Tasks define actions to run when testing submissions. Examples include building student code, checking for forbidden syntax elements, or running the generated test executable.
This module provides tasks as trees (type Tree.t
), so tasks can be more easily re-used and composed.
Running tasks automatically handles exceptions and timeouts.
A single task, possibly with subtasks (see k
).
Task continuation of type 'b k
: Upon completion, a task produces a value of some type 'a
, and a list of subtasks from 'a
to 'b
.
A list of tasks, which start by accepting a value of type 'a
and produce a result of type 'b
.
val nil : ('a, 'a) tasks
Create a task list from a regular list. All tasks must have the same input and output type (e.g. unit
); if that is not desired, use the tasks
constructors directly.
unsnoc t1 ts
splits the non-empty list cons t1 ts
into its initial elements and final element, see unsnoc
.
val pp_task_failure : Stdlib.Format.formatter -> task_failure -> unit
Calling failf "..." ...
will raise an exception that aborts the task runner with a formatted message.
Like failf
, but with a plain string.
type summary = {
label : string option;
elapsed_task : Mtime.span;
does not include subtasks
*)elapsed_total : Mtime.span;
includes subtasks
*)subtasks : summary list;
}
type 'a st_out = ('a, task_failure) Stdlib.result
If the last task completed successfully with a value of x
, then Ok x
. Otherwise the failure reason of the task that failed.
run ~timeout t x
runs the task tree t
with the initial input x
, and the given timeout (default: no timeout).
val task1 : ?timeout:Mtime.span -> ?label:string -> ('a -> 'b) -> ('c, 'd) tree
Run a single function as a task, without any subtasks
Create a task tree from a list of tasks, the task itself will do nothing but return the list of subtasks.
Modify the final result of a task tree, without creating an additional task. Note: since f
runs inside the final task, its side-effects should be minimal: any exceptions will be raised inside an existing task, and the existing task's timeout will include f
. If that is undesirable, run f
inside a new subtask with then_subtask
.
val pure : 'a -> ('b, 'c) tree
spawning k
runs as the list of tasks produced by applying k
to the task's input
accumulating f ts
uses f
to combine the output of each task into a running accumulator value
collecting ts
pushes the outputs of each task onto a list
collecting'
is like collecting
, except with an empty initial list and a final List.rev
step so that the results are in order; the result is a tasks
rather than a list
val pp_summary : failure:bool -> ?show_anon:bool -> unit -> summary Fmt.t
val pp_state_out : 'a Fmt.t -> Stdlib.Format.formatter -> 'b st_out -> unit
Test_runner
Library for creating a runner, which then drives the testing process.
module Task : sig ... end
Set up, build, and run tests using first-class tasks.
module Std_task : sig ... end
Common tasks and tasks for the standard test setup.
module Entry_point : sig ... end
Entry points for creating test driver executables from a task tree.
module P_run = Common.P_run
Re-export of Common.P_run
. Tasks spawning subprocesses can use parts of this module.
Thread_counter.Counter
val lock_if : bool -> Stdlib.Mutex.t -> (unit, 'a, 'a) Common.Ctx_util.t
Note: we enforce that spawned threads don't raise uncaught exceptions, which in theory changes the semantics of threads. The value of being able to report stray exceptions outweighs the slim chance anyone would rely on being able to ignore exceptions in threads.
val try_return : 'a group -> 'b -> unit
val create_counter : unit -> t
val get_thread_count : 'a group -> int
val join_group :
+ leftover_thread_limit:int ->
+ timeout:Mtime.span ->
+ 'a group ->
+ int
Wait for threads in a group to complete. Group must be finished first.
type thread_group_err =
| ThreadLimitReached of int
| ThreadsLeftOver of {
}
| ExceptionRaised of {
main : bool;
exn_info : Common.Util.exn_info;
}
val spawn_thread_group :
+ ?thread_limit:int ->
+ t ->
+ ('a -> 'b) ->
+ 'c ->
+ ('b, Common.Util.exn_info) Stdlib.result group
Create a group that runs the given function, then sets the return value as the return value of the group.
val collect_thread_group :
+ ?leftover_limit:(int * Mtime.span) ->
+ 'a group ->
+ 'b finished * int
Wait for a group to finish then join its threads (join_group
).
val check_thread_group_result :
+ ?leftover_limit:(int * Mtime.span) ->
+ ('a, Common.Util.exn_info) Stdlib.result finished ->
+ int ->
+ ('b, thread_group_err list) Stdlib.result
Check the return value of collect_thread_group
val run_in_thread_group :
+ ?thread_limit:int ->
+ ?leftover_limit:(int * Mtime.span) ->
+ t ->
+ ('a -> 'b) ->
+ 'c ->
+ ('d, thread_group_err list) Stdlib.result
Combines spawn_thread_group
, collect_thread_group
, and check_thread_group_result
.
val string_of_thread_group_err : thread_group_err -> string
val string_of_thread_group_errs : thread_group_err list -> string
exception ThreadGroupErrs of thread_group_err list
val thread_group_result_to_exn :
+ ('a, thread_group_err list) Stdlib.result ->
+ 'b
CounterInstance.Thread
Like Stdlib.Thread
, but with counted threads
Thread_counter.CounterInstance
val instance : Counter.t
module Thread : sig ... end
Like Stdlib.Thread
, but with counted threads
Thread_counter.Debug
Thread_counter.ThreadH
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val length : 'a t -> int
val stats : 'a t -> Stdlib__Hashtbl.statistics
val to_seq_values : 'a t -> 'a Stdlib.Seq.t
Thread_counter
module Debug : sig ... end
module ThreadH : sig ... end
module Counter : sig ... end
module CounterInstance () : sig ... end
Threads_alerts.Event_alerting
include sig ... end
val new_channel : unit -> 'a channel
Return a new channel.
send ch v
returns the event consisting in sending the value v
over the channel ch
. The result value of this event is ()
.
receive ch
returns the event consisting in receiving a value from the channel ch
. The result value of this event is the value received.
val always : 'a -> 'a event
always v
returns an event that is always ready for synchronization. The result value of this event is v
.
choose evl
returns the event that is the alternative of all the events in the list evl
.
wrap ev fn
returns the event that performs the same communications as ev
, then applies the post-processing function fn
on the return value.
wrap_abort ev fn
returns the event that performs the same communications as ev
, but if it is not selected the function fn
is called after the synchronization.
guard fn
returns the event that, when synchronized, computes fn()
and behaves as the resulting event. This enables computing events with side-effects at the time of the synchronization operation.
val sync : 'a event -> 'a
'Synchronize' on an event: offer all the communication possibilities specified in the event to the outside world, and block until one of the communications succeed. The result value of that communication is returned.
val select : 'a event list -> 'a
'Synchronize' on an alternative of events. select evl
is shorthand for sync(choose evl)
.
val poll : 'a event -> 'a option
Non-blocking version of Event.sync
: offer all the communication possibilities specified in the event to the outside world, and if one can take place immediately, perform it and return Some r
where r
is the result value of that communication. Otherwise, return None
without blocking.
Threads_alerts.Thread_alerting
include sig ... end
val create : ('a -> 'b) -> 'a -> t
Thread.create funct arg
creates a new thread of control, in which the function application funct arg
is executed concurrently with the other threads of the domain. The application of Thread.create
returns the handle of the newly created thread. The new thread terminates when the application funct arg
returns, either normally or by raising the Thread.Exit
exception or by raising any other uncaught exception. In the last case, the uncaught exception is printed on standard error, but not propagated back to the parent thread. Similarly, the result of the application funct arg
is discarded and not directly accessible to the parent thread.
See also Domain.spawn
if you want parallel execution instead.
val self : unit -> t
Return the handle for the thread currently executing.
val id : t -> int
Return the identifier of the given thread. A thread identifier is an integer that identifies uniquely the thread. It can be used to build data structures indexed by threads.
Exception raised by user code to initiate termination of the current thread. In a thread created by Thread.create
funct
arg
, if the Thread.Exit
exception reaches the top of the application funct arg
, it has the effect of terminating the current thread silently. In other contexts, there is no implicit handling of the Thread.Exit
exception.
Raise the Thread.Exit
exception. In a thread created by Thread.create
, this will cause the thread to terminate prematurely, unless the thread function handles the exception itself. Fun.protect
finalizers and catch-all exception handlers will be executed.
To make it clear that an exception is raised and will trigger finalizers and catch-all exception handlers, it is recommended to write raise Thread.Exit
instead of Thread.exit ()
.
delay d
suspends the execution of the calling thread for d
seconds. The other program threads continue to run during this time.
val join : t -> unit
join th
suspends the execution of the calling thread until the thread th
has terminated.
Re-schedule the calling thread without suspending it. This function can be used to give scheduling hints, telling the scheduler that now is a good time to switch to other threads.
Thread.default_uncaught_exception_handler
will print the thread's id, exception and backtrace (if available).
Suspend the execution of the calling thread until at least one character or EOF is available for reading (wait_timed_read
) or one character can be written without blocking (wait_timed_write
) on the given Unix file descriptor. Wait for at most the amount of time given as second argument (in seconds). Return true
if the file descriptor is ready for input/output and false
if the timeout expired. The same functionality can be achieved with Unix.select
.
val select :
+ Unix.file_descr list ->
+ Unix.file_descr list ->
+ Unix.file_descr list ->
+ float ->
+ Unix.file_descr list * Unix.file_descr list * Unix.file_descr list
Same function as Unix.select
. Suspend the execution of the calling thread until input/output becomes possible on the given Unix file descriptors. The arguments and results have the same meaning as for Unix.select
.
Same function as Unix.waitpid
. wait_pid p
suspends the execution of the calling thread until the process specified by the process identifier p
terminates. Returns the pid of the child caught and its termination status, as per Unix.wait
.
sigmask cmd sigs
changes the set of blocked signals for the calling thread. If cmd
is SIG_SETMASK
, blocked signals are set to those in the list sigs
. If cmd
is SIG_BLOCK
, the signals in sigs
are added to the set of blocked signals. If cmd
is SIG_UNBLOCK
, the signals in sigs
are removed from the set of blocked signals. sigmask
returns the set of previously blocked signals for the thread.
wait_signal sigs
suspends the execution of the calling thread until the process receives one of the signals specified in the list sigs
. It then returns the number of the signal received. Signal handlers attached to the signals in sigs
will not be invoked. The signals sigs
are expected to be blocked before calling wait_signal
.
Thread.set_uncaught_exception_handler fn
registers fn
as the handler for uncaught exceptions.
If the newly set uncaught exception handler raise an exception, default_uncaught_exception_handler
will be called.
Threads_alerts
Like Stdlib_alerts
, but for threads. This is separate to avoid an unnecessary dependency on the threads
library
module type Thread_alerting = sig ... end
module type Event_alerting = sig ... end
module Thread_alerting : Thread_alerting
module Event_alerting : Event_alerting
Threads_alerts.Event_alerting
include sig ... end
val new_channel : unit -> 'a channel
Return a new channel.
send ch v
returns the event consisting in sending the value v
over the channel ch
. The result value of this event is ()
.
receive ch
returns the event consisting in receiving a value from the channel ch
. The result value of this event is the value received.
val always : 'a -> 'a event
always v
returns an event that is always ready for synchronization. The result value of this event is v
.
choose evl
returns the event that is the alternative of all the events in the list evl
.
wrap ev fn
returns the event that performs the same communications as ev
, then applies the post-processing function fn
on the return value.
wrap_abort ev fn
returns the event that performs the same communications as ev
, but if it is not selected the function fn
is called after the synchronization.
guard fn
returns the event that, when synchronized, computes fn()
and behaves as the resulting event. This enables computing events with side-effects at the time of the synchronization operation.
val sync : 'a event -> 'a
'Synchronize' on an event: offer all the communication possibilities specified in the event to the outside world, and block until one of the communications succeed. The result value of that communication is returned.
val select : 'a event list -> 'a
'Synchronize' on an alternative of events. select evl
is shorthand for sync(choose evl)
.
val poll : 'a event -> 'a option
Non-blocking version of Event.sync
: offer all the communication possibilities specified in the event to the outside world, and if one can take place immediately, perform it and return Some r
where r
is the result value of that communication. Otherwise, return None
without blocking.
Threads_alerts.Thread_alerting
include sig ... end
val create : ('a -> 'b) -> 'a -> t
Thread.create funct arg
creates a new thread of control, in which the function application funct arg
is executed concurrently with the other threads of the domain. The application of Thread.create
returns the handle of the newly created thread. The new thread terminates when the application funct arg
returns, either normally or by raising the Thread.Exit
exception or by raising any other uncaught exception. In the last case, the uncaught exception is printed on standard error, but not propagated back to the parent thread. Similarly, the result of the application funct arg
is discarded and not directly accessible to the parent thread.
See also Domain.spawn
if you want parallel execution instead.
val self : unit -> t
Return the handle for the thread currently executing.
val id : t -> int
Return the identifier of the given thread. A thread identifier is an integer that identifies uniquely the thread. It can be used to build data structures indexed by threads.
Exception raised by user code to initiate termination of the current thread. In a thread created by Thread.create
funct
arg
, if the Thread.Exit
exception reaches the top of the application funct arg
, it has the effect of terminating the current thread silently. In other contexts, there is no implicit handling of the Thread.Exit
exception.
Raise the Thread.Exit
exception. In a thread created by Thread.create
, this will cause the thread to terminate prematurely, unless the thread function handles the exception itself. Fun.protect
finalizers and catch-all exception handlers will be executed.
To make it clear that an exception is raised and will trigger finalizers and catch-all exception handlers, it is recommended to write raise Thread.Exit
instead of Thread.exit ()
.
delay d
suspends the execution of the calling thread for d
seconds. The other program threads continue to run during this time.
val join : t -> unit
join th
suspends the execution of the calling thread until the thread th
has terminated.
Re-schedule the calling thread without suspending it. This function can be used to give scheduling hints, telling the scheduler that now is a good time to switch to other threads.
Thread.default_uncaught_exception_handler
will print the thread's id, exception and backtrace (if available).
Suspend the execution of the calling thread until at least one character or EOF is available for reading (wait_timed_read
) or one character can be written without blocking (wait_timed_write
) on the given Unix file descriptor. Wait for at most the amount of time given as second argument (in seconds). Return true
if the file descriptor is ready for input/output and false
if the timeout expired. The same functionality can be achieved with Unix.select
.
val select :
+ Unix.file_descr list ->
+ Unix.file_descr list ->
+ Unix.file_descr list ->
+ float ->
+ Unix.file_descr list * Unix.file_descr list * Unix.file_descr list
Same function as Unix.select
. Suspend the execution of the calling thread until input/output becomes possible on the given Unix file descriptors. The arguments and results have the same meaning as for Unix.select
.
Same function as Unix.waitpid
. wait_pid p
suspends the execution of the calling thread until the process specified by the process identifier p
terminates. Returns the pid of the child caught and its termination status, as per Unix.wait
.
sigmask cmd sigs
changes the set of blocked signals for the calling thread. If cmd
is SIG_SETMASK
, blocked signals are set to those in the list sigs
. If cmd
is SIG_BLOCK
, the signals in sigs
are added to the set of blocked signals. If cmd
is SIG_UNBLOCK
, the signals in sigs
are removed from the set of blocked signals. sigmask
returns the set of previously blocked signals for the thread.
wait_signal sigs
suspends the execution of the calling thread until the process receives one of the signals specified in the list sigs
. It then returns the number of the signal received. Signal handlers attached to the signals in sigs
will not be invoked. The signals sigs
are expected to be blocked before calling wait_signal
.
Thread.set_uncaught_exception_handler fn
registers fn
as the handler for uncaught exceptions.
If the newly set uncaught exception handler raise an exception, default_uncaught_exception_handler
will be called.
Framework for sandboxed testing of OCaml code.
This framework consists of a number of libraries and executables for testing untrusted OCaml code. Designed for running programming exercises fully automatically and at scale.
The following public components are included in the package:
Ast_check
AST checker.Test_lib
Library of common functionality for writing tests.Test_runner
Library for creating a runner, which then drives the testing process.Stdlib
variants and overrides:
Stdlib_alerts
Variants of Stdlib
, but with signature items that can be restricted annotated with alerts.Stdlib_components
Adapted from Stdlib
, with different components in different modules. In particular, a safe (pure) subset of OCaml features can be enabled by opening a subset of modules defined here.Overrides
The following components are intended for use within framework code only:
Common
Functionality common to multiple components.Modules and tools for overriding which standard library values are available to student code.
Stdlib
variantsVariants of Stdlib
. These are modules that contain values like ( = )
and further modules like List
.
Stdlib_alerts
Variants of Stdlib
, but with signature items that can be restricted annotated with alerts.Stdlib_components
Adapted from Stdlib
, with different components in different modules. In particular, a safe (pure) subset of OCaml features can be enabled by opening a subset of modules defined here.Prefer Stdlib_alerts
for new code. Unlike Stdlib_components
, it provides feedback beyond just Error: Unbound value
if a prohibited item is used.
Modules that are intended to be opened at the top level (what the compiler calls "pervasives"). Usually this contains a module called Stdlib
, as well as the contents of that module (e.g. via open
). It may also contain e.g. a module called Thread
.
Overrides
Signature_builder
Library and PPX rewriter for building interfaces from existing interfaces by selectively adding and removing interface items.