Haskell and memoization of pure function results

Possible duplicate:
When is automatic automation in GHC Haskell?

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

+6
source share
1 answer

I voted for closing, but the short answer is:

GHC does not perform automatic memoization of functions, and this is probably good because it complicates spatial complexity. In addition, memoirization is not a very solvable problem at all, since it requires that the function argument be comparable for equality, which is actually impossible for all types (e.g. functions).

Haskell has loose semantics. GHC provides a more or less challenge to the cost model. Although the overhead of lazy grades at high levels of optimization is not so bad because of the stringency analyzer.

It is very easy to implement memoization in Haskell using a lazy evaluation. However, be careful in using space.

fib' :: (Integer -> Integer) -> Integer -> Integer fib' f 0 = 0 fib' f 1 = 1 fib' fn | 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 

Actually it is not so fast, and it is a leak of space, but it captures the general idea. You can learn more about the Haskell wiki .

+11
source

Source: https://habr.com/ru/post/925223/


All Articles