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

烂漫一生 提交于 2019-11-29 06:21:13

问题


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 point the pure functional approach (i.e. the same method called with the same parameters does the same thing) at a problem where typically (in an OO program) I would need to cache data.

  • Do we just admit that there might need to be an actor in the program which is not immutable (i.e. the cache). I just watched a presentation by Joe Armstrong on infoq and he seemed pretty dogmatic in this regard!

  • Do we just admit that looking up data might be expensive (because we can never cache it)? If so, how can we control, for example, the load on some shared resource (e.g. a database)

  • Is there some magic fairy dust, which I don't know about yet, which solves the whole problem and then makes a nice cup of tea afterwards.

Certainly a google search for "Erlang Cache" seems to return a fair few results...


回答1:


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.




回答2:


Memoize the function. A cache is just a list/dictionary, and hence can be implemented in a purely functional way.




回答3:


There is no reason a Cache and a Functional language can't live together. To be functional you just have to obey the constraint that calling the same function with the same arguments you get the same answer.

For instance: get_data(Query, CacheCriteria)

Just because the get_data uses a cache doesn't mean it's not functional. As long as calling get_data with the same Query, and CacheCriteria arguments always returns the same value then the language can be considered functional.



来源:https://stackoverflow.com/questions/997276/how-does-one-use-cached-data-in-a-functional-language-such-as-erlang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!