Skip to content

Instantly share code, notes, and snippets.

@Eckankar
Created November 4, 2012 16:02
Show Gist options
  • Save Eckankar/4012403 to your computer and use it in GitHub Desktop.
Save Eckankar/4012403 to your computer and use it in GitHub Desktop.
Memoized fibonacci using closures in Standard ML
(* 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