[erlang-questions] memoization (was: Re: [Fwd: Re: Functional Programming])

Colin Meyer cmeyer@REDACTED
Fri Aug 31 18:07:11 CEST 2007


Hi,

I've been following the recent Erlang hype, and reading Joe Armstrong's
excellent book. Fun stuff.

On Wed, Aug 29, 2007 at 05:56:08PM -0400, Zac Brown wrote:
> Hi:
> 
>     You're correct that it is recursion and the calls you listed are
> corrected. Essentially this is a stack-expanding recursive call which
> are bad because you're building up your recursive calls and if its a big
> number, you risk blowing the stack. The best way to define this function
> in the manner you have is as follows:
> 
> fac(N) - > fac_helper(N, 1).
> 
> fac_helper(1, Tot) -> Tot;
> fac_helper(N, Tot) ->
>     fac_helper(N - 1, Tot * N).

In stateful languages, a typical optimization would be to memoize the
return value of stable functions. This style of recursive factorial
calculator is a classic candidate for memoization. On each call to a
function, a cache is examined to find if the result is already known. If
the result is known, it is returned. Otherwise it is calculated, cached
for future use and returned.

Do Erlang programmers have an analogous optimization for not repeatedly
calculating the same values?

I recognize that one could create a process to wrap the function, and
cache the results in the process dictionary. That doesn't feel very
Erlangish to me.

Thanks,
-Colin.



More information about the erlang-questions mailing list