Module Kw

module Kw: sig .. end

General utility functions


Author(s): Keith Waclena


Combinators and Operators


val id : 'a -> 'a
Identity function
val k : 'a -> 'b -> 'a
Constant-function combinator
val const : 'a -> 'b -> 'a
val kite : 'a -> 'b -> 'b
KI combinator (name from Smullyan): KI = λab.b
val w : ('a -> 'a -> 'b) -> 'a -> 'b
argument-doubling combinator

Infix function composition, right-associative
val b : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b
Haskell's (.)
val (&) : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b
val (@.) : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b
val ($) : ('a -> 'b) -> ('b -> 'c) -> 'a -> 'c
Function composition. 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
argument-flipping combinator
val flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c
val s : ('a -> 'b -> 'c) -> ('a -> 'b) -> 'a -> 'c
the S combinator
val (|>) : 'a -> ('a -> 'b) -> 'b
Function application (like unix pipe)
val (>>) : ('a -> 'b) -> 'a -> 'b
Infix function application, right-associative
val y : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b
Y combinator
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
diag combinator
val (&&&) : ('a -> 'b) -> ('c -> 'd) -> 'a * 'c -> 'b * 'd
cross combinator
val on : ('a -> 'a -> 'b) -> ('c -> 'a) -> 'c -> 'c -> 'b
From Haskell prelude.

Typical usage:

# List.sort (on compare fst)

val (%) : ('a -> 'b, unit, string) Pervasives.format -> 'a -> 'b
Python-like sprintf operator Use (>>) for formats with more than one escape: "foo %d %s" % 12 >> "yikes"
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


Arithmetic


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
Algol 68-style variable increment: let x = ref 0 in x +:= 1
val (-:=) : int Pervasives.ref -> int -> unit
Algol 68-style variable deccrement: let x = ref 0 in x -+:= 1
val rem : int -> int -> int
Floored remainder and division
val quo : int -> int -> int

Fold Helpers


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 accumulator
pred : predicate testing x for accumulatability
acc : the accumulator
x : the current value being folded
val foldwhen : ('a -> 'b -> 'a) -> ('b -> bool) -> 'a -> 'b -> 'a
foldwhen: synonym for Kw.foldwhen_left
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 accumulator
pred : predicate testing x for accumulatability
x : the current value being folded
acc : the accumulator

Fold Helpers for List Accumulators


val 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 accumulatability
acc : the accumulator
x : the current value being folded

Timing, Timeouts and Sleeping


val 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 milliseconds
Author(s): Olivier Andrieu, Keith Waclena (added EINTR restart)
val elapsed : ('a -> 'b) -> 'a -> float * 'b
elapsed f x: measure elapsed wall-clock time it takes to evaluate (f x).
Returns the pair (s,r) where s is the elapsed time in seconds and r is the result of (f x)
f : the function
x : its parameter
val timer : ?t:float * float -> unit -> float * float
return elapsed user and system times since time 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)
Time the execution of a function application

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 runtime
f : function to apply
x : value to which to apply f
val timefmt : 'a * (float * float) -> 'a * string
format the timings result of time above as a string
Returns pair of x, str where str is a formatted version of the two floats from time
exception Timeout
exception used by with_timeout
val with_timeout : int -> ('a -> 'b) -> ('a -> 'b) -> 'a -> 'b
apply f to arg with a timeout
Returns f arg if application completes in less then timeout seconds, else returns default arg
time : timeout in seconds
default : function applied to arg for result if f arg is timed-out
f : function to apply to arg
arg : value f or default is applied to

Finalization


exception Finally of exn
exception used internally by finalize; should never escape
val finalize : ('a -> 'b) -> ('a -> 'c) -> 'a -> 'b
finalization functional

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.
Returns (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 applied
newdir : 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.

Defaults


val default : 'a -> ('b -> 'a) -> 'b -> 'a
Given default def f x, apply f to x, returning def if it raises an exception, else returning f x
Returns f x or else def
def : some default value
f : some function to apply to x
x : some value
val 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.
Returns b, if a, else c
a : value to test against: value we don't want
b : value to replace a with
c : value to return or replace

Exceptions


val ignex : ('a -> unit) -> 'a -> unit
ignex f x: evaluate f x, ignoring any exceptions.
f : some function to apply to x
x : some value
val catch : ('a -> 'b) -> 'a -> 'b option
apply f to x, returning None if an exception was raised, else return Some (f x)
Returns Some (f x) or else None
f : some function to apply to x
x : some value
exception No_exception
an exception for catchex indicating No_exception was raised!
val catchex : ('a -> 'b) -> 'a -> 'b option * exn
apply f to x, returning (None, ex) if an exception was raised, where ex is the exception, else return Some (f x), No_exception
Returns Some (f x, No_exception) or else None, exception
f : some function to apply to x
x : some value
val 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 apply
x : 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 apply
x : value f is applied to
val 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 other
that : convert an exception to that
f : the function to apply
val convert : exn -> exn -> ('a -> 'b) -> 'a -> 'b
Deprecated.You should use Kw.changex
convert exeception this (raised by f x) to that
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 value
val 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 do
f : the function

Options


val get : 'a option -> 'a
Return value x of an option (Some x)
Raises Not_found if option is None
Returns the value
val some : 'a -> 'a option
make x:'a into an 'a option
Returns the option
x : some value
val something : 'a option -> bool
Return 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 default
val optmap : ('a -> 'b) -> 'a option -> 'b option
Apply f to an option type o, returning None or Some (f (get o))
f : the function
o : the option

Tuples


val pairup : 'a -> 'b -> 'a * 'b
pairup a b: return the 2-tuple (a,b)
val pairmap : ('a -> 'b) -> 'a * 'a -> 'b * 'b
Apply a function to each element of a 2-tuple
Returns 2-tuple of results
f : function ('a -> 'b) to apply

Bit-Fiddling


val ctpop : int -> int
ctpop: count the population of an unsigned integer: how many bits are set to 1?

Strings


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).
Returns list of strings
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 text
sep : the separator string (default: " \t\r\n")
val join : ?sep:string -> string list -> string
Synonym for String.concat with a default separator string.
sep : the separator string (default: " ")

Lists


val cons : 'a -> 'a list -> 'a list
function equivalent to (::) if that operator were syntactically legal
val snoc : 'a list -> 'a -> 'a list
reverse cons; = 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 accumulator
x : some value
val rev : 'a list -> 'a list
Synonym for List.rev.
val len : 'a list -> int
Synonym for List.length.
val nth : int -> 'a list -> 'a
Like List.nth but taking the parameters in the "correct order" :-)
Returns the desired element
n : index of desired list element (0-based)
list : the list from which to extract the desired element
val upto : int -> int -> int list
Return a list of n+1-m integers from m upto n inclusive; tail recursive.
val (--) : int -> int -> int list
infix version of upto
val iota : int -> int list
Return a list of n integers from 0 to n-1
val map : ('a -> 'b) -> 'a list -> 'b list
Short name for List.map.
val iter : ('a -> unit) -> 'a list -> unit
Short name for List.iter.
val rev : 'a list -> 'a list
Short name for List.rev.
val foldl : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a
Short name for 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
Short name for 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.


Maxima and Minima


val maxvalue : 'a list -> 'a
Return maximum value in a list of ordered values
val minvalue : 'a list -> 'a
Return minimum value in a list of ordered values

Messages


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!" ...
Returns fun level msg, a function that will print string msg to stderr if int level is <= the current verbosity level
reference : an int ref encoding the current verbosity level
val 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.
Returns f x
comma : string (suggesting an unfinished line) to terminate msg (default: ", ")
over : string to print following comma after f x is evaluated
lvl : verbosity level
msg : message to print
f : some function to apply to x
x : some value
type 'a protected = {
   prot : unit Weak.t;
   desc : 'a;
}
val protect : 'a -> 'a protected

Hash Tables


val hashincr : ?init:int Pervasives.ref ->
?incf:(int Pervasives.ref -> unit) ->
('a, int Pervasives.ref) Hashtbl.t -> 'a -> unit
add entries to a "counting" hash table
Returns ()
init : the initial value (default: ref 1)
incf : the incrementer function (default: Pervasives.incr)
tbl : hash table
key : key

Program's External Environment


val argvbut0 : unit -> string array
Return array of command-line arguments less argv0
val getusername : unit -> string
Return username of owner of this process
val env : ?default:string -> string -> string
env ?default name returns the value of environment variable name as a string
Returns value of environment variable
default : default value returned if name not in environment (default: "")
name : name of environment variable
val 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 change
new' : the new value of the variable
f : function to apply to x

Functionals


val mapints : (int -> 'a) -> int -> int -> 'a list
map f i across each integer i in the closed interval a,z, gathering the results in a list
f : function int -> 'a to apply
a : lowerbound of the interval
z : upperbound of the interval
val foreach : (int -> 'a) -> int -> int -> unit
execute f i (for side-effect) for each integer i in the closed interval a,z
f : function int -> unit to apply
a : lowerbound of the interval
z : upperbound of the interval
val foldir : (int -> 'a -> 'a) -> 'a -> int -> int -> 'a
foldir f right-associatively across the closed integer interval a,z (not tail-recursive)
f : function int -> 'a -> 'a to apply
a : lowerbound of the interval
z : upperbound of the interval
val foldil : ('a -> int -> 'a) -> 'a -> int -> int -> 'a
foldil f left-associatively across the closed integer interval a,z (tail-recursive)
f : function 'a -> int -> 'a to apply
a : lowerbound of the interval
z : upperbound of the interval
val 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
go
before 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
go
before returning ().
val conjunction : ('a -> bool) list -> 'a -> bool
return a predicate which is the conjunction of the predicates in a list
val disjunction : ('a -> bool) list -> 'a -> bool
return a predicate which is the disjunction of the predicates in a list
val pam : ('a -> 'b) list -> 'a -> 'b list
Apply many functions to one value

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 apply
x : value to apply each function to
val 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 predicate
list : the list
val 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 predicate
list : the list
module Count: sig .. end
Counting Accumulators