Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell and memoization of pure function results [duplicate]

Possible Duplicate:
When is memoization automatic in GHC Haskell?

As a consequence, pure function always returns the same value for a fixed input. That said, does Haskell (more precisely GHC) automatically cache (memoize) these results if there is enough memory (question 1) and does developer have any control on it (question 2)?

like image 238
Cartesius00 Avatar asked Sep 12 '12 14:09

Cartesius00


People also ask

Is a memoized function pure?

A memoized function should be a pure function. This means the function execution does not mutate. When called with a certain input, it should always returns the same value regardless of how many times the function will be called.

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.

Is memoization same as caching?

Memoization is a specific form of caching that is used in dynamic programming. The purpose of caching is to improve the performance of our programs and keep data accessible that can be used later.

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.


1 Answers

I voted to close, but short answer:

GHC does not do any automatic memoization of functions, and that is probably a good thing because it would make space complexity even harder to reason about. Also, memoization is not in general a very solvable problem, since it requires the argument of the function be comparable for equality which is not really possible for all types (for example, functions).

Haskell has non-strict semantics. GHC provides a, more or less, call by need cost model. Although the overhead of lazy evaluation at high optimization levels is not that bad because of the strictness analyzer.

It is very easy to implement memoization in Haskell using lazy evaluation. Be careful about space usage though.

fib' :: (Integer -> Integer) -> Integer -> Integer
fib' f 0 = 0
fib' f 1 = 1
fib' f n | n > 1 = (f (n - 1)) + ((f (n - 2))

slow_fib :: Integer -> Integer
slow_fib = fib' slow_fib

fibs :: [Integer]
fibs = map (fib' memo_fib) [0..] 

memo_fib :: Integer -> Integer
memo_fib n = fibs !! n

This is actually not that fast, and is a space leak, but captures the general idea. You can learn more on the Haskell wiki.

like image 176
Philip JF Avatar answered Nov 11 '22 18:11

Philip JF