[erlang-questions] beginner: implement a cache/memoization

Bengt Kleberg <>
Wed Oct 31 10:06:12 CET 2007


greetings,

i was going to recommend loop data in a list but a quick search gave me 
this example for the Bernoulli function (found on 
http://en.literateprograms.org/Bernoulli_numbers_(Erlang)):

bernoulli(N) ->
     Name = bernoulli,
     case ets:info(Name) of
     undefined -> ets:new(Name, [public, named_table]);
     _ -> true
     end,
     case ets:lookup(Name, N) of
     [] ->
         Val = bernoulli_i(N),
         ets:insert(Name, {N, Val}),
         Val;
     [{N, Val}] -> Val
     end.

changing to another function and limiting the ets table to 1000 items is 
left as an exercise for the reader :-).


bengt
Those were the days...
    EPO guidelines 1978: "If the contribution to the known art resides
    solely in a computer program then the subject matter is not
    patentable in whatever manner it may be presented in the claims."


On 2007-10-31 08:02, Maximillian Dornseif wrote:
> I have a function which takes 1-5 sec to compute and will be called about 15
> times a minute. Since many of the queries occure repeated I was thinking of
> caching the last 1000 results (Each about 200 bytes).
> 
> The simpelest solution would be to create a ringbuffer. What would be the
> appropriate datastructure? A Queue? This would mean that for every cace
> check I would have to call lists:to_list/1.
> 
> An alternative would be a "Real" LRU cache. Is there an elegant
> datastructure for that? Or do I have to go with an ets table an a cache
> expiry process?
> 
> Regards
> 
> Maximillian



More information about the erlang-questions mailing list