Created
November 4, 2012 16:02
-
-
Save Eckankar/4012403 to your computer and use it in GitHub Desktop.
Memoized fibonacci using closures in Standard ML
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
(* Regular fibonacci *) | |
fun fib 0 = 0 | |
| fib 1 = 1 | |
| fib n = fib (n-1) + fib (n-2); | |
(* Fibonacci using closures for memoization *) | |
local | |
fun fib_c f n = | |
case f n of | |
SOME v => (v, f) | |
| NONE => | |
let val (v', f') = fib_c f (n-1) | |
val (v'', f'') = fib_c f' (n-2) | |
val res = v' + v'' | |
in (res, fn x => if x = n then SOME res else f'' x) end | |
fun fib_init 0 = SOME 0 | |
| fib_init 1 = SOME 1 | |
| fib_init _ = NONE | |
in | |
val fib' = #1 o fib_c fib_init | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment