Skip to content

Instantly share code, notes, and snippets.

@Zeta611
Created March 13, 2020 14:26
Show Gist options
  • Save Zeta611/478a5319f8625780ca295f1c24b01834 to your computer and use it in GitHub Desktop.
Save Zeta611/478a5319f8625780ca295f1c24b01834 to your computer and use it in GitHub Desktop.
[memoize] General memoization function #algorithm
let memoize ?(size = 100) f =
let tbl = Hashtbl.create size in
let rec g = fun x ->
try Hashtbl.find tbl x
with Not_found ->
let v = f g x in
Hashtbl.add tbl x v;
v
in
f g
let fib self = function
| 0 | 1 -> 1
| n -> self (n - 1) + self (n - 2)
let fib_mem = memoize fib
let _ =
print_int (fib_mem 50);
print_newline ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment