Skip to content

Instantly share code, notes, and snippets.

@dpetzold
Created August 5, 2010 18:54
Show Gist options
  • Save dpetzold/510191 to your computer and use it in GitHub Desktop.
Save dpetzold/510191 to your computer and use it in GitHub Desktop.
-module(db).
-export([new/0, write/3, destroy/1, delete/2, read/2, match/2, test/0]).
new() -> [].
write(Key, Element, Db) -> [{Key, Element}|Db].
read(Key, [Head | Tail]) ->
{K, V} = Head,
if
Key == K -> {ok, V};
true -> read(Key, Tail)
end;
read(_Key, []) -> {error, instance}.
match(Element, Db) ->
match_acc(Element, Db, []).
match_acc(Element, [Head | Tail], Matches) ->
{K, V} = Head,
if
V == Element -> match_acc(Element, Tail, [K | Matches]);
true -> match_acc(Element, Tail, Matches)
end;
match_acc(_Element, _Db, Matches) -> Matches.
delete(Key, Db) -> delete_acc(Key, Db, []).
delete_acc(Key, [Head | Tail], Items) ->
{K, _V} = Head,
if
Key == K -> delete_acc(Key, Tail, Items);
true -> delete_acc(Key, Tail, [Head | Items])
end;
delete_acc(_Key, _Db, Items) -> Items.
destroy(Db) -> [].
test() ->
Db = new(),
io:format("~p~n", [Db]),
Db1 = write(franceso, london, Db),
io:format("~p~n", [Db1]),
Db2 = write(lelle, stockholm, Db1),
io:format("~p~n", [Db2]),
Ret = read(franceso, Db2),
io:format("~p~n", [Ret]),
Db3 = write(joern, stockholm, Db2),
io:format("~p~n", [Db3]),
Ret1 = read(ola, Db3),
io:format("~p~n", [Ret1]),
Ret2 = match(stockholm, Db3),
io:format("~p~n", [Ret2]),
Db4 = delete(lelle, Db3),
io:format("~p~n", [Db4]),
Ret3 = match(stockholm, Db4),
io:format("~p~n", [Ret3]).
-module(my_db).
-export([start/0, stop/0, read/1, write/2, match/1, delete/1, loop/1]).
-export([init/0]).
start() ->
register(my_db, spawn(my_db, init, [])),
ok.
init() ->
loop([]).
stop() ->
my_db ! stop,
ok.
loop(Db) ->
receive
{request, Pid, {read, Key}} ->
Ret = db:read(Key, Db),
reply(Pid, Ret),
loop(Db);
{request, Pid, {match, Element}} ->
Ret = db:match(Element, Db),
reply(Pid, Ret),
loop(Db);
{request, Pid, {write, Key, Element}} ->
D = db:write(Key, Element, Db),
reply(Pid, ok),
loop(D);
{request, Pid, {delete, Key}} ->
D = db:delete(Key, Db),
reply(Pid, ok),
loop(D);
stop -> true;
_Other -> io:format("Unknown~p~n", [_Other])
end.
call(Message) ->
my_db ! {request, self(), Message},
receive
{reply, Reply} -> Reply
end.
reply(Pid, Reply) ->
Pid ! {reply, Reply}.
read(Key) ->
call({read, Key}).
write(Key, Element) ->
call({write, Key, Element}).
match(Element) ->
call({match, Element}).
delete(Key) ->
call({delete, Key}).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment