Created
March 13, 2020 14:26
-
-
Save Zeta611/478a5319f8625780ca295f1c24b01834 to your computer and use it in GitHub Desktop.
[memoize] General memoization function #algorithm
This file contains hidden or 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 ?(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