Skip to content

Instantly share code, notes, and snippets.

@buunguyen
Created June 10, 2012 20:29
Show Gist options
  • Save buunguyen/2907222 to your computer and use it in GitHub Desktop.
Save buunguyen/2907222 to your computer and use it in GitHub Desktop.
Memoization in Bike
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