Source

spotlib / lib / base.mli

(** Basic functinons. They are accessible via [open Spotlib.Spot] *)

(** {6 Misc things } *)

type ('a, 'b) result = [ `Ok of 'a | `Error of 'b ]
(** Result/Either monad *)

val sprintf : ('a, unit, string) format -> 'a
(** [Printf.sprintf] is available without tying [Printf.] *)

val memoize : ('c -> 'd) -> 'c -> 'd
(** Memozation by hash *)

val time : ('a -> 'b) -> 'a -> 'b * float
(** simple profiling *)

(** {6 Printf style errors } *)

val failwithf : ('a, unit, string, 'b) format4 -> 'a
val invalid_argf : ('a, unit, string, 'b) format4 -> 'a

(** {6 Function compositions } *)

val (^.) : ('b -> 'c) -> ('a -> 'b) -> ('a -> 'c)
val (&.) : ('b -> 'c) -> ('a -> 'b) -> ('a -> 'c)
val (@@) : ('b -> 'c) -> ('a -> 'b) -> ('a -> 'c)
(** funciton composition: Haskell's (.) *)

external (&) : ('a -> 'b) -> 'a -> 'b = "%apply"
external (&~) : (f:'a -> 'b) -> 'a -> 'b = "%apply"
(** Haskell's ($) *)

external (|!) : 'a -> ('a -> 'b) -> 'b = "%revapply"
external (|>) : 'a -> ('a -> 'b) -> 'b =  "%revapply"
(** F#'s (|>) *)

external id : 'a -> 'a = "%identity"
external (!&) : _ -> unit = "%ignore"

(** {6 Exception handling } *)

exception Finally of exn * exn

val protect    : f:('a -> 'b) -> 'a -> finally: ('a -> unit) -> 'b
val catch      : f:('a -> 'b) -> 'a -> ('b, exn) result
val try_ignore : f:('a -> unit) -> 'a -> unit

val try_bool   : f:('a -> 'b) -> 'a -> bool
(** [true] at success *)

(** {6 Imperative operations } *)

val imp : 'a -> ('a ref -> 'b) -> ('a * 'b)
val imp_ : 'a -> ('a ref -> 'b) -> 'a
(** IMPerative application tamed a bit functionally. A sort of.

    [imp init f] creates a reference of [init],
    then run the function [f] over this reference.
    It returns the final contents of the reference.
*)

val with_ref : 'a ref -> 'a -> (unit -> 'b) -> 'b
(** [with_ref r v f] run a thunk [f] with setting [r := v] temporarily.
    [r] is set back to its original value after [f ()] finishes or
    raises an exceptoin.
*)