Source

spotlib / lib / base.ml

The default branch has multiple heads

Full commit
type ('a, 'b) result = [ `Ok of 'a | `Error of 'b ]

let memoize f =
  let cache = Hashtbl.create 101 in
  fun v -> try Hashtbl.find cache v with Not_found ->
    let r = f v in
    Hashtbl.replace cache v r;
    r

let memoize_rec f =
  let cache = Hashtbl.create 101 in
  let rec g v = 
    try Hashtbl.find cache v with Not_found ->
      let r = f g v in
      Hashtbl.replace cache v r;
      r
  in
  g

external (&) : ('a -> 'b) -> 'a -> 'b = "%apply"
external (&~) : (f:'a -> 'b) -> 'a -> 'b = "%apply"
external (|!) : 'a -> ('a -> 'b) -> 'b = "%revapply"
external (|>) : 'a -> ('a -> 'b) -> 'b =  "%revapply"

let ( ** ) f g = fun x -> f (g x)
let ( *< ) = ( ** )
let ( *> ) f g = fun x -> g (f x)
external power : float -> float -> float = "caml_power_float" "pow" "float"

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

let time f v =
  let start = Unix.gettimeofday () in
  let res = f v in
  let end_ = Unix.gettimeofday () in
  res, end_ -. start

let imp init f =
  let r = ref init in
  let res = f r in
  !r, res

let imp_ init f = fst (imp init f)
 
(* Printf *)
let sprintf = Printf.sprintf
let ksprintf = Printf.ksprintf
let (!%) = Printf.sprintf
let (!!%) = Format.eprintf

let with_ref r v f =
  let back_v = !r in
  r := v;
  Exn.protect f () ~finally:(fun () -> r := back_v)
    

let with_oc oc f = 
  Exn.protect f oc ~finally:close_out

let with_ic ic f = 
  Exn.protect f ic ~finally:close_in

let (|-) res f = f res; res

let flip f x y = f y x
let (~~) g ~f = g f
let flipf = (~~)