What is the lifetime of a memoized value in a functional language like Haskell?

一笑奈何 提交于 2019-11-30 06:50:51

Haskell does not automatically memoize function calls, precisely because this would quickly consume tons of memory. If you do memoziation yourself, you get to choose at what scope the function is memoized. For example, let's say you have the fibonacci function defined like this:

fib n = fibs !! n
    where fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

Here the memoization is only done within one call to fib, whereas if you leave fibs at the top level

fib n = fibs !! n

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

then the memoized list is kept until the garbage collector can determine that there are no more ways to reach fibs from any part of your program.

My idea is that maybe memoized values are simply "scoped" to something in the program (for example to the current continuation, call stack, etc.), but I was unable to find something practical on the subject.

This is correct. Specifically, when you see something like:

fun x y = let
    a = .....
    b = ....
    c = ....
in ....

or an equivalent where clause, the values a, b and c may not be computed until actually used (or they may be computed right away because the strictness analyser can proove that the values would be evaluated later anyway). But when those values depend on current function parameters (here x and y), the runtime will most likely not remember every combination of x and y and the resulting a, b and c.

Note also, that in a pure language, it is also okay to not remember the values at all - this is only practical insofar as memory is cheaper than CPU time.

So the answer to your question is: there is no such thing as lifetime of intermediary results in Haskell. All one can say is that the evaluated value will be there when needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!