module Kw:sig
..end
val id : 'a -> 'a
val k : 'a -> 'b -> 'a
val const : 'a -> 'b -> 'a
val kite : 'a -> 'b -> 'b
val w : ('a -> 'a -> 'b) -> 'a -> 'b
val b : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b
(.)
val (&) : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b
val (@.) : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b
val ($) : ('a -> 'b) -> ('b -> 'c) -> 'a -> 'c
f $ g
is fun x -> g (f x)
.
This is Haskell's $
operator.
val (|-) : ('a -> 'b) -> ('b -> 'c) -> 'a -> 'c
val c : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c
val flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c
val s : ('a -> 'b -> 'c) -> ('a -> 'b) -> 'a -> 'c
val (|>) : 'a -> ('a -> 'b) -> 'b
val (>>) : ('a -> 'b) -> 'a -> 'b
val y : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b
val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b
val curry : ('a * 'b -> 'c) -> 'a -> 'b -> 'c
curry f x y
: converts an uncurried function to a curried function.val uncurry : ('a -> 'b -> 'c) -> 'a * 'b -> 'c
uncurry f (x,y)
: converts a curried function to a function on pairs.val ( *** ) : ('a -> 'b) -> ('a -> 'c) -> 'a -> 'b * 'c
val (&&&) : ('a -> 'b) -> ('c -> 'd) -> 'a * 'c -> 'b * 'd
val on : ('a -> 'a -> 'b) -> ('c -> 'a) -> 'c -> 'c -> 'b
Typical usage:
# List.sort (on compare fst)
val (%) : ('a -> 'b, unit, string) Pervasives.format -> 'a -> 'b
val tap : ('a -> 'b) -> 'a -> 'a
tap f x
: Allows application of a function in the middle of a pipe sequence without disturbing the sequence.
x |> tap f
evaluates to x, but has the side effect of f x
. Useful for debugging.
From BatPervasives.
val after : ('a -> 'b) -> 'a -> 'c -> 'c
after f x y
: evaluate f x
(for side-effect), then return y
.
Also useful for avoiding begin
/ end
in conditional branches, e.g.
if valid x then S.add x set else after (warning "bad: %s") x set
val (~++) : int -> int
succ
as a prefix operator: ~++0 = 1
val (~--) : int -> int
pred
as a prefix operator: ~--1 = 0
val (+:=) : int Pervasives.ref -> int -> unit
let x = ref 0 in x +:= 1
val (-:=) : int Pervasives.ref -> int -> unit
let x = ref 0 in x -+:= 1
val rem : int -> int -> int
val quo : int -> int -> int
val foldwhen_left : ('a -> 'b -> 'a) -> ('b -> bool) -> 'a -> 'b -> 'a
foldwhen_left cons pred acc x
: return cons acc x
when pred x
, else acc
Helpful with left-folds. Example: compute sum of non-negative ints in a list:
foldl (foldwhen_left (+) ((<) 0) (~-4--3) = 6
cons
: function to combine x
and the accumulatorpred
: predicate testing x
for accumulatabilityacc
: the accumulatorx
: the current value being foldedval foldwhen : ('a -> 'b -> 'a) -> ('b -> bool) -> 'a -> 'b -> 'a
val foldwhen_right : ('a -> 'b -> 'b) -> ('a -> bool) -> 'a -> 'b -> 'b
foldwhen_right cons pred x acc
: same as Kw.foldwhen_left
, but for right-folds,
so takes a right-handed cons
cons
: function to combine x
and the accumulatorpred
: predicate testing x
for accumulatabilityx
: the current value being foldedacc
: the accumulatorval conswith : ('a -> 'b) -> 'b list -> 'a -> 'b list
conswith f acc x
: is f x :: acc
.
foldl (conswith succ) = foldl (fun acc x -> succ x :: acc)
So: foldl (conswith succ) [] (0--3) =
[4; 3; 2; 1]
val conswhen : ('a -> bool) -> 'a list -> 'a -> 'a list
conswhen pred acc x
: return x :: acc
when pred x
, else acc
foldl (conswhen (flip (<) 10)) [] (1--1_000) = [9; 8; 7; 6; 5; 4; 3; 2; 1]
pred
: predicate testing x
for accumulatabilityacc
: the accumulatorx
: the current value being foldedval restart_on_EINTR : ('a -> 'b) -> 'a -> 'b
restart_on_EINTR f x
: evaluate f x
, restarting if evaluation is interrupted by EINTR
.
f
is presumed to be using a "slow" Unix system call.
Typical usage:
restart_on_EINTR (Unix.waitpid []) pid
val msleep : int -> unit
msleep ms
sleeps for ms
millisecondsval elapsed : ('a -> 'b) -> 'a -> float * 'b
elapsed f x
: measure elapsed wall-clock time it takes to evaluate (f x)
.(s,r)
where s
is the elapsed time in seconds and r
is the result of (f x)
f
: the functionx
: its parameterval timer : ?t:float * float -> unit -> float * float
t
For example, {let t = timer () in (* do stuff *); let elapsed = timer ~t ()}
Returns pair of (u,s)
where u are elapsed seconds of user time and are elapsed seconds of system time
t
: pair (u,s)
such as returned by a previous application of timer
val time : ?gc:bool -> int -> ('a -> 'b) -> 'a -> 'b * (float * float)
Return the time it takes to execute f x
, averaged over n
executions, performing (if ~gc
is true) a complete gc before each
execution (and not counting the time it takes to perform the gc).
Returns pair of f x, (u,s)
where u are elapsed seconds of user time and are elapsed seconds of system time
gc
: if true (the default), do a Gc.full_major
and Gc.compact
before each execution (gc times are not counted)n
: number of times over which to average the runtimef
: function to applyx
: value to which to apply f
val timefmt : 'a * (float * float) -> 'a * string
time
above as a stringx, str
where str is a formatted version of the two floats from time
exception Timeout
with_timeout
val with_timeout : int -> ('a -> 'b) -> ('a -> 'b) -> 'a -> 'b
f
to arg
with a timeoutf arg
if application completes in less then timeout
seconds, else returns default arg
time
: timeout in secondsdefault
: function applied to arg
for result if f arg
is timed-outf
: function to apply to arg
arg
: value f
or default
is applied toexception Finally of exn
val finalize : ('a -> 'b) -> ('a -> 'c) -> 'a -> 'b
Given finalize body final arg
, execute body arg
, making sure to
execute final arg
afterwards, no matter what. If an exception is
thrown in the evaluation of body arg
, we propagate it upwards
after executing final arg
.
Returns whatever body arg
returns
body
: function to apply to arg
final
: function to execute afterwards, also applied to arg
val withcwd : (string -> string -> 'a) -> string -> 'a
withcwd f newdir
cd's to newdir
and then returns (f olddir newdir)
, restoring the previous cwd.
In other words, evaluate f
"in" newdir
, giving it the names of the old and new directories as parameters.(f olddir newdir)
, string olddir
being the path of the "old" cwd (which will be restored) and string newdir
being the path of the new cwd when f
is appliednewdir
: directory to be temporary current working directory during evaluation of f
val prog1 : 'a -> ('b -> 'c) -> 'b -> 'a
prog1 result f x
: like Lisp's prog1, return result
after
evaluating f x
for a side-effect.val default : 'a -> ('b -> 'a) -> 'b -> 'a
default def f x
, apply f
to x
, returning def
if it raises an exception, else returning f x
f x
or else def
def
: some default valuef
: some function to apply to xx
: some valueval whenever : 'a -> 'a -> 'a -> 'a
whenever a b
is the function that returns b
whenever it's applied to a
,
returning the value it's applied to otherwise. Example: Kwstring.map (whenever '\n' ' ') str
replaces newlines in str
with spaces.b
, if a
, else c
a
: value to test against: value we don't wantb
: value to replace a
withc
: value to return or replaceval ignex : ('a -> unit) -> 'a -> unit
ignex f x
: evaluate f x
, ignoring any exceptions.f
: some function to apply to xx
: some valueval catch : ('a -> 'b) -> 'a -> 'b option
f
to x
, returning None
if an exception was raised, else return Some (f x)
f x
) or else None
f
: some function to apply to xx
: some valueexception No_exception
catchex
indicating No_exception was raised!val catchex : ('a -> 'b) -> 'a -> 'b option * exn
f
to x
, returning (None, ex)
if an exception was raised, where ex
is the exception,
else return Some (f x), No_exception
f x
, No_exception) or else None, exception
f
: some function to apply to xx
: some valueval succeeds : ?exc:exn -> ('a -> 'b) -> 'a -> bool
succeeds ?exc f x
computes f x
and returns true if the function
returns without raising exception exc
, and false if it raises exc
; any
other exception is passed upward.exc
: exception that indicates failure (default: any exception)f
: function to applyx
: value f
is applied to
Example: succeeds (String.index "foo") 'X'
returns false
val exceptional : ('a -> 'b) -> 'a -> bool
exceptional f x
: does (f x)
raise an exception?f
: function to applyx
: value f
is applied toval changex : ?this:exn -> exn -> ('a -> 'b) -> 'a -> 'b
changex ?this that f x
: apply (f x)
, converting exception this
to that
.this
: only convert this exception, no otherthat
: convert an exception to that
f
: the function to applyval convert : exn -> exn -> ('a -> 'b) -> 'a -> 'b
val trying : ('a -> 'b) list -> 'a -> 'b
trying fs x
: return (List.hd fs) x
unless an exception is raised, in which case recur.
So, apply each function in fs
in turn until one succeeds, and return that value.
If none succeed, raise Failure "trying"
.
Raises Failure
"trying" if no function succeeds
Returns the result of the first successful application
fs
: non-empty list of functions to try t apply to x
x
: some valueval foldex : ?exn:exn -> ('a -> 'b -> 'a) -> 'a -> 'b -> 'a
foldex ?exn f init x
: fold over calls to f x
until an exception occurs.
When exn
is given, then if exn
is raised, the accumulator is returned.
When exn
is not given, then if any exception is raised, the accumulator
is returned. Thus, providing exn
is more precise.
If no exception (or, given exn
, no matching exception) is raised, the result is
undefined (i.e., no termination).
Tail-recursive. Example:
let c = open_in "/etc/passwd" in finalize (foldex ~exn:End_of_file (fun a c -> input_line c :: a) []) close_in c
exn
: the exception; if not given, any will dof
: the functionval get : 'a option -> 'a
x
of an option
(Some x)
Not_found
if option
is None
val some : 'a -> 'a option
x:'a
into an 'a option
x
: some valueval something : 'a option -> bool
true
if option
is Some _
, false
if None
val optdef : 'a -> 'a option -> 'a
optdef def option
: return x
if option is Some x
, else def
def
: the defaultval optmap : ('a -> 'b) -> 'a option -> 'b option
f
to an option type o
, returning None
or Some (f (get o))
f
: the functiono
: the optionval pairup : 'a -> 'b -> 'a * 'b
pairup a b
: return the 2-tuple (a,b)
val pairmap : ('a -> 'b) -> 'a * 'a -> 'b * 'b
f
: function ('a -> 'b)
to applyval ctpop : int -> int
ctpop
: count the population of an unsigned integer: how many bits are set to 1?val split : ?merge:bool -> ?sep:string -> string -> string list
split ?merge ?sep str
: split str
on a separator character (any of the characters in sep
).merge
: consider runs of consecutive chars from sep
to be one
separator; so ~merge:false
is good for /etc/passwd while ~merge:true
is good for lexing "words" from textsep
: the separator string (default: " \t\r\n"
)val join : ?sep:string -> string list -> string
String.concat
with a default separator string.sep
: the separator string (default: " "
)val cons : 'a -> 'a list -> 'a list
(::)
if that operator were syntactically legalval snoc : 'a list -> 'a -> 'a list
c cons
val rcons : 'a list -> 'a -> 'a list
val consup : 'a -> 'a list
consup x
: return a list containing x
val consof : ('a -> 'b) -> 'b list -> 'a -> 'b list
consof f acc x
= f x :: acc
; handy for use with folds.
E.g. Kwstring.foldl (consof Char.code) [] "012" = [50; 49; 48]
f
: function to apply to x
acc
: some list accumulatorx
: some valueval rev : 'a list -> 'a list
List.rev
.val len : 'a list -> int
List.length
.val nth : int -> 'a list -> 'a
List.nth
but taking the parameters in the "correct order" :-)n
: index of desired list element (0-based)list
: the list from which to extract the desired elementval upto : int -> int -> int list
val (--) : int -> int -> int list
val iota : int -> int list
val map : ('a -> 'b) -> 'a list -> 'b list
List.map
.val iter : ('a -> unit) -> 'a list -> unit
List.iter
.val rev : 'a list -> 'a list
List.rev
.val foldl : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a
List.fold_left
.val foldl1 : ('a -> 'a -> 'a) -> 'a list -> 'a
foldl1 f list
: a variant of foldl
that has no starting value argument, and thus must be applied to non-empty lists.val foldr : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b
List.fold_right
.
Not tail recursive.
val foldr1 : ('a -> 'a -> 'a) -> 'a list -> 'a
foldr1 f list
: a variant of foldr
that has no starting value argument, and thus must be applied to non-empty lists.
Not tail recursive.
val maxvalue : 'a list -> 'a
val minvalue : 'a list -> 'a
val verbosefun : 'a Pervasives.ref ->
?chan:Pervasives.out_channel ->
?close:bool ->
?flush:bool ->
?nl:bool -> ?initial:bool -> ?myself:string -> 'a -> string -> unit
verbosefun ref
returns a function suitable for printing verbose messages
typical usage:
let verbosity = ref (default 0 int_of_string (env ~default:"0" "VERBOSITY"))
let verbose = verbosefun verbosity
... verbose 1 "a little chatty" ...
... verbose 2 "somewhat chattier" ...
... verbose 10 "holy smokes!" ...fun level msg
, a function that will print string msg
to stderr if int level is <= the current verbosity levelreference
: an int ref
encoding the current verbosity levelval verboselyfun : (?chan:Pervasives.out_channel ->
?close:bool ->
?flush:bool ->
?nl:bool -> ?initial:bool -> ?myself:string -> int -> string -> unit) ->
?comma:string -> ?over:string -> int -> string -> ('a -> 'b) -> 'a -> 'b
verbosely level msg f x
prints a verbose message, then evaluates f x
, then prints
a "finished" message.f x
comma
: string (suggesting an unfinished line) to terminate msg
(default: ", "
)over
: string to print following comma
after f x
is evaluatedlvl
: verbosity levelmsg
: message to printf
: some function to apply to xx
: some valuetype 'a
protected = {
|
prot : |
|
desc : |
val protect : 'a -> 'a protected
val hashincr : ?init:int Pervasives.ref ->
?incf:(int Pervasives.ref -> unit) ->
('a, int Pervasives.ref) Hashtbl.t -> 'a -> unit
init
: the initial value (default: ref 1
)incf
: the incrementer function (default: Pervasives.incr
)tbl
: hash tablekey
: keyval argvbut0 : unit -> string array
val getusername : unit -> string
val env : ?default:string -> string -> string
env ?default name
returns the value of environment variable name
as a stringdefault
: default value returned if name
not in environment (default: ""
)name
: name of environment variableval unsetenv : string -> int
unsetenv var
: deletes the variable named var
from the environment.
If name does not exist in the environment, then the function
succeeds, and the environment is unchanged.
Returns 0
on success, ~-1
on error; errors aren't supposed to occur
val withenv : string -> string -> ('a -> 'b) -> 'a -> 'b
withenv var new' f x
: evaluate f x
with environment variable
var
set to value new'
; var
is then restored to its original
value.
Normally succeeds but may raise a Failure
exception if the
underlying system calls fail.
Returns whatever f x
evaluates to
var
: the variable to changenew'
: the new value of the variablef
: function to apply to x
val mapints : (int -> 'a) -> int -> int -> 'a list
f i
across each integer i
in the closed interval a,z
, gathering the results in a listf
: function int -> 'a
to applya
: lowerbound of the intervalz
: upperbound of the intervalval foreach : (int -> 'a) -> int -> int -> unit
f i
(for side-effect) for each integer i
in the closed interval a,z
f
: function int -> unit
to applya
: lowerbound of the intervalz
: upperbound of the intervalval foldir : (int -> 'a -> 'a) -> 'a -> int -> int -> 'a
f
right-associatively across the closed integer interval a,z
(not tail-recursive)f
: function int -> 'a -> 'a
to applya
: lowerbound of the intervalz
: upperbound of the intervalval foldil : ('a -> int -> 'a) -> 'a -> int -> int -> 'a
f
left-associatively across the closed integer interval a,z
(tail-recursive)f
: function 'a -> int -> 'a
to applya
: lowerbound of the intervalz
: upperbound of the intervalval nest : int -> ('a -> 'a) -> 'a -> 'a
val aslongas : ('a -> bool) -> ('b -> 'a) -> 'b -> 'a
aslongas pred f x
: while-loop functional for functions with side-effects.
Evaluate f x
repeatedly as long as pred result
is true (where
result
is the result of f x
), returning the final result
.
Tail-recursive.
Example: aslongas (fun _ -> Random.bool ()) print_endline "go"
might print:
go go go gobefore returning
()
.val until : ('a -> bool) -> ('b -> 'a) -> 'b -> 'a
until pred f x
: until-loop functional for functions with side-effects.
Evaluate f x
repeatedly until pred result
is true (where
result
is the result of f x
), returning the final result
.
Tail-recursive.
Example: until (fun _ -> Random.bool ()) print_endline "go"
might print:
go gobefore returning
()
.val conjunction : ('a -> bool) list -> 'a -> bool
val disjunction : ('a -> bool) list -> 'a -> bool
val pam : ('a -> 'b) list -> 'a -> 'b list
Sort of the converse of map -- what did Backus call this? Applies
each of the n
functions in list funcs
to value x
returning
list of n
values.
Returns list of values
funcs
: list of functions ('a -> 'b)
to applyx
: value to apply each function toval all : ('a -> bool) -> 'a list -> bool
all p list
: Applied to a predicate and a list, any determines if all of the elements of the
list satisfy the predicate.p
: the predicatelist
: the listval any : ('a -> bool) -> 'a list -> bool
any p list
: Applied to a predicate and a list, any determines if any element of the
list satisfies the predicate.p
: the predicatelist
: the listmodule Count:sig
..end