Memoization in Erlang?

Thomas Johnsson <>
Thu Feb 2 15:38:12 CET 2006


Ulf Wiger (AL/EAB) wrote:

>
>Another approach might be:
>
>-define(eval(Expr) -> memo:eval(fun() -> Expr end)).
>
>eval(F) when is_function(F, 0) ->
>  case memo_db:lookup(F) of
>     {ok, Cached} -> Cached;
>     error ->
>        Value = F(),
>        memo_db:store(F, Value),
>        Value
>  end
>
>
>
>This has the wonderful advantage that you can
>memoize any expression. F uniquely identifies
>the closure, including bound environment, so
>it will serve as a key.
>  
>
What, you can do function equality in Erlang?? I hadn't realized....
That's highly dubious ... When are two function equal according the the 
Erlang implementation?


25> fun()-> x end.
#Fun<erl_eval.20.102880425>
26> (fun()-> x end) == (fun()-> x end).
true
27> (fun(X)-> X end) == (fun(X)-> X end).
true
28> (fun(X)-> 2*X end) == (fun(X)-> X+X end).
false
29> (fun(X)-> X end) == (fun(Y)-> Y end).
false
30>

-- Thomas




More information about the erlang-questions mailing list