Simple example for Erlang memoization

后端 未结 2 2138
Happy的楠姐
Happy的楠姐 2021-02-14 07:31

Suppose you have a simple function, which can get quite expensive for large values:

fact(0) -> 1;
fact(N) -> N * fact(N - 1).

Where can I

2条回答
  •  一生所求
    2021-02-14 08:05

    Depending on your case, you can also use the process dictionary for memoization:

    fact(0) -> 1;
    fact(N) ->
        case erlang:get({'fact', N}) of
            F when is_integer(F) ->
                F;
            'undefined' ->
                F = N * fact(N-1),
                erlang:put({'fact', N}, F),
                F
        end.
    

提交回复
热议问题