Sep 4

I am currently reading a book on Erlang Programming by Francesco Cesarini:Erlang Programming .  It is quite well written.  In it, there is some programming exercises.  One of them is to write a simple key value DB.  So I wrote one.  Here it is:

-module(db).
-export([new/0,destroy/1,write/3,delete/2,read/2,match/2]).
new()->Db=[],
Db.

destroy(Db)->_=Db,
ok.

write(Key,Element,Db)->NewDb = [{Key,Element}|delete(Key,Db)],
NewDb.

delete(Key,Db)->case Db of
[H|T] ->
case H of
{Key,_} -> T;
_-> [H|delete(Key,T)]
end;
[] ->Db
end.

read(Key,Db)->case Db of
[H|T] ->
case H of
{Key,Element} ->Element;
_->read(Key,T)
end;
[] ->{error,instance}
end.
match(Element,Db)->case Db of
[H|T] ->
case H of
{Key,Element}->[Key|match(Element,T)];
_ ->match(Element,T)
end;
[] ->Db
end.
To use it:

1> Db = db:new().
[]
2> Db1 = db:write(book,elrang,Db).
[{book,elrang}]
3> Db2 = db:write(author,francesco,Db1).
[{author,francesco},{book,elrang}]
5> db:read(author,Db2).
francesco
6> db:match(elrang,Db2).
[book]

Not very useful but it shows how to write simple program in erlang.