Created
June 5, 2012 20:53
-
-
Save osa1/2877817 to your computer and use it in GitHub Desktop.
memoization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let memoize f = | |
let table = Hashtbl.create 10 in | |
fun p -> try Hashtbl.find table p | |
with Not_found -> | |
let _ = print_string "not found (memoize)\n" in | |
let v = f p in | |
let _ = Hashtbl.add table p v in | |
v | |
let memoize2 f = | |
let table = Hashtbl.create 10 in | |
fun p1 -> try Hashtbl.find table p1 | |
with Not_found -> | |
let _ = print_string "not found (memoize2)\n" in | |
let v = f p1 in | |
let _ = Hashtbl.add table p1 v in | |
memoize v | |
let memoize3 f = | |
let table = Hashtbl.create 10 in | |
fun p1 -> try Hashtbl.find table p1 | |
with Not_found -> | |
let _ = print_string "not found (memoize3)\n" in | |
let v = f p1 in | |
let _ = Hashtbl.add table p1 v in | |
memoize2 v | |
(* why this doesn't work? *) | |
let rec memoize_gen f x = | |
if x = 1 | |
then let table = Hashtbl.create 10 in | |
fun p -> try Hashtbl.find table p | |
with Not_found -> | |
let _ = "not found\n" in | |
let v = f p in | |
let _ = Hashtbl.add table p v in | |
v | |
else memoize_gen (memoize_gen f 1) (x-1) | |
let test = | |
let fun1 = memoize_gen (fun a -> | |
let _ = print_string "running the function with one param\n" in | |
a) 1 | |
in [fun1 1; fun1 1; fun1 1] | |
let test2 = | |
let fun1 = memoize_gen (fun a b c -> | |
let _ = print_string "running the function\n" in | |
a + b + c) 3 | |
in [fun1 3 2 1;fun1 3 2 1; fun1 3 2 1] | |
let test3 = | |
memoize (fun a -> | |
memoize (fun b -> | |
memoize (fun c -> let _ = print_string "memoized inner function\n" in | |
a + b + c))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment