Custom Search

Tuesday, February 16, 2010

Storing Data in a Hash - Erlang

Came across this nice example in the Erlang mailing list for storing data in an hashmap.

-module(db_server).

-export([start/0, init/1, write/2, read/1, delete/1]).

start() ->
register(server, spawn(db_server, init, [dict:new()])).

init(Records) ->
receive
{add, Pid, Key, Value} ->
RecordsNew = dict:store(Key, Value, Records),
Pid ! {ok, Key, Value},
init(RecordsNew);
{show, Pid, Key} ->
case dict:find(Key, Records) of
{ok, Value} -> Pid ! {ok, Value};
error ->  Pid ! {error, no_such_value}
end,
init(Records);
{delete, Pid, Key} ->
RecordsNew = dict:erase(Key, Records),
Pid ! {ok, ok},
init(RecordsNew)           
end.

write(Key, Value) ->
server ! {add, self(), Key, Value},
receive Res ->
Res
end.

read(Key) ->
server ! {show, self(), Key},
receive Res ->
Res
end.

delete(Key) ->
server ! {delete, self(), Key},
receive Res ->
Res
end.



No comments: