Created
June 10, 2012 20:29
-
-
Save buunguyen/2907222 to your computer and use it in GitHub Desktop.
Memoization in Bike
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
func memoize(f) { | |
var cache = { | |
member_missing: func() { null } | |
}; | |
return func recur(n) { | |
cache[n] || (cache[n] = f(recur, n)); | |
}; | |
} | |
var fib = func(n) { | |
n < 2 ? 1 : fib(n-1) + fib(n-2) | |
}; | |
var m_fib = memoize(func(recur, n) { | |
n < 2 ? 1 : recur(n-1) + recur(n-2); | |
}); | |
load 'stopwatch.bk'; | |
var watch = Bike.Stopwatch.create( ).start( ); | |
println('fib(20) = {0} (elapsed: {1}ms)', fib(20), watch.stop()); | |
watch.reset().start(); | |
println('m_fib(20) = {0} (elapsed: {1}ms)', m_fib(20), watch.stop()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment