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

Matthew O'Gorman mogorman@REDACTED
Fri Aug 31 18:24:52 CEST 2007


i have this
memo.erl:
-module (memo).
-export ([y/1, memoize/1, fib/1]).

y (F) ->
    F (fun (X) ->    (y (F)) (X) end).

memoize (Tab, F) ->
    fun (B) ->
            fun (C) ->
                    case ets:lookup (Tab, C) of
                        [] ->
                            R = (F (B)) (C),
                            ets:insert (Tab, {C, R }),
                            R;
                        [{C, R}] ->
                            R
                    end
            end
    end.

memoize (F) ->
    fun (X) ->
            Tab = ets:new (?MODULE, [ private ]),
            Ans = (y (memoize (Tab, F))) (X),
            ets:delete (Tab),
            Ans
    end.

fibimpl (P) ->
    fun (0) -> 1;
        (1) -> 1;
        (N) when N > 1 -> P (N - 1) + P (N - 2)
    end.

fib (N) ->
    (memoize (fun fibimpl/1)) (N).



memoize.erl:
-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



mog



More information about the erlang-questions mailing list