(* Opérateur de mémoïsation, pour des arguments d'un type quelconque *)

module Make(X: sig
  type t
  val equal: t -> t -> bool
  val hash: t -> int
end) = struct

  module H = Hashtbl.Make(X)

  let memo_rec ff =
    let h = H.create 5003 in
    let rec f x =
      try H.find h x
      with Not_found -> let v = ff f x in H.add h x v; v
    in
    f

end

(* test *)

let () =
  let module M = Make(struct type t = int let equal = (=) let hash x = x end) in
  let fib =
    M.memo_rec (fun fib n -> if n <= 1 then n else fib (n-2) + fib (n-1)) in
  assert (fib 10 = 55);
  assert (fib 14 = 377)


This document was generated using caml2html