How does one use cached data in a functional language such as Erlang?

后端 未结 3 688
眼角桃花
眼角桃花 2020-12-30 04:08

I\'ve been reading a bit lately about functional languages. Coming from 10+ years of OO development, I\'m finding it difficult to get my head around how on earth one can poi

3条回答
  •  滥情空心
    2020-12-30 04:19

    It is data which must be immutable in Erlang, not actors.

    Long-lived actors normally live in a tail-recursive function, the arguments of which serve as their state and certainly can change between calls.

    -module(cache).
    -export([start/0, get_c/1, put_c/2, clear/1]).
    
    start() -> register(spawn(fun () -> loop(dict:new()) end), cache).
    
    loop(Dict) -> receive
                    {get, From, Key} -> From ! {cache_result, Key, dict:fetch(Key, Dict)};
                    {set, Key, Value} -> NewDict = dict:store(Key, Value, Dict),
                                         loop(NewDict);
                    %% etc.
                  end
    
    put_c(Key, Value) -> cache ! {set, Key, Value}
    %% etc.
    

    When you call put_c, the actor's "state" changes even though all data involved is immutable.

提交回复
热议问题