Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Why does this work -- an example of memoization?

Hi I am looking at this example from Memoization:

memoized_fib :: Int -> Integer
memoized_fib = (map fib [0 ..] !!)
    where fib 0 = 0
          fib 1 = 1
          fib n = memoized_fib (n-2) + memoized_fib (n-1)

I am just wondering why this even work, since for me if you call memoized_fib(n-2) then you are "creating" a new list and doing things with it and after your return from it the list containing partial result would be gone? So memorized_fib(n-1) won't benefit from it at all?

like image 922
Bob Fang Avatar asked Jan 05 '14 15:01

Bob Fang


People also ask

Does Haskell do memoization?

Fortunately, it is possible to memoize a function without side effects thanks to Haskell's nature of lazy evaluation. The following memoize function takes a function of type Int -> a and returns a memoized version of the same function.

What is memoization why and when would you use it?

In programming, memoization is an optimization technique that makes applications more efficient and hence faster. It does this by storing computation results in cache, and retrieving that same information from the cache the next time it's needed instead of computing it again.

What are the benefits of memoization?

It helps avoid waste by removing the need to recalculate values that have already been produced as part of a previous call. The benefits of memoization will be less apparent in functions that are simple to begin with or infrequently called.

What is memoization in data structure?

In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.


Video Answer


1 Answers

memoized_fib is a CAF, which is as good as a literal constant in avoiding creation of new stuff. No variables ⇒ no things to bind new stuff to ⇒ no creation of new stuff (in simplified terms).

like image 52
n. 1.8e9-where's-my-share m. Avatar answered Nov 07 '22 06:11

n. 1.8e9-where's-my-share m.