scala people say...
Mar. 14th, 2013 12:03 am"With programming a Fibonacci function I ran into memoization. That is
really useful.
Normal Fibonacci:
With memoization:
When calculating Fibonacci 50 the normal function takes 18 minutes and
the memoization version takes 3 seconds. So that is a very respectable
improvement. But how does memoization work?
"
really useful.
Normal Fibonacci:
def fib(n: Long): Long = n match {
case 0 | 1 => n
case _ => fib(n - 1) + fib(n - 2)
}
With memoization:
def fibMem: Stream[Long] = {
def tail(h: Long, n: Long): Stream[Long] = h #:: tail(n, h + n)
tail(0, 1)
}
When calculating Fibonacci 50 the normal function takes 18 minutes and
the memoization version takes 3 seconds. So that is a very respectable
improvement. But how does memoization work?
"