Commits

camlspotter committed 52b4e27

Xhashtbl.memoize

Comments (0)

Files changed (2)

   match f (find_opt tbl k) with
   | None -> Hashtbl.remove tbl k
   | Some v -> Hashtbl.replace tbl k v
+
+let memoize tbl f k =
+  try 
+    Hashtbl.find tbl k 
+  with
+  | Not_found ->
+      let v = f k in
+      Hashtbl.replace tbl k v;
+      v
 val replace_list : ('a, 'b) Hashtbl.t -> ('a * 'b) list -> unit
-val of_list : int -> ('a * 'b) list -> ('a, 'b) Hashtbl.t
-val to_list : ('a, 'b) Hashtbl.t -> ('a * 'b) list
-val find_opt : ('a, 'b) Hashtbl.t -> 'a -> 'b option
-val alter : ('a, 'b) Hashtbl.t -> 'a -> ('b option -> 'b option) -> unit
+val of_list      : int -> ('a * 'b) list -> ('a, 'b) Hashtbl.t
+val to_list      : ('a, 'b) Hashtbl.t -> ('a * 'b) list
+val find_opt     : ('a, 'b) Hashtbl.t -> 'a -> 'b option
+val alter        : ('a, 'b) Hashtbl.t -> 'a -> ('b option -> 'b option) -> unit
+val memoize      : ('a, 'b) Hashtbl.t -> ('a -> 'b) -> 'a -> 'b