2006/12/22

Erlang fib

-module(fib).
-export([fib/1, fib2/1, start/0, server/1]).

fib(1) -> 1;

fib(2) -> 1;

fib(N) ->
fib(N-1) + fib(N-2).

fib2(N) ->
fib_server ! {N, self()},
receive
{ok, Value} ->
Value;
_ ->
Result = fib2(N - 1) + fib2(N - 2),
fib_server ! {add, N, Result},
Result
end.

server(Dict) ->
receive
{N, Client} ->
case dict:find(N, Dict) of
{ok, Value} ->
Client ! {ok, Value},
fib:server(Dict);
_ -> Client ! nil,
fib:server(Dict)
end;
{add, N, Result} ->
fib:server(dict:store(N, Result, Dict));
dump -> io:format("~p~n", [Dict]),
fib:server(Dict)
end.

start() ->
Dict = dict:new(),
Dict1 = dict:store(1, 1, Dict),
Dict2 = dict:store(2, 1, Dict1),
Pid = spawn(fib, server, [Dict2]),
register(fib_server, Pid).

0 件のコメント: