Skip to content

Commit adee4f5

Browse files
committed
chapter 3: exercice 3.4
1 parent 6d0a400 commit adee4f5

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

chap3/db.erl

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
-module (db).
2+
-export ([new/0,
3+
destroy/1,
4+
write/3,
5+
delete/2,
6+
read/2,
7+
match/2,
8+
test_db/0]).
9+
10+
11+
new() ->
12+
[].
13+
14+
destroy(_Db) ->
15+
ok.
16+
17+
write(Key, Element, [{Key, _Value}|T]) ->
18+
[{Key, Element}|T];
19+
write(Key, Element, []) ->
20+
[{Key, Element}];
21+
write(Key, Element, [H|T]) ->
22+
[H|write(Key, Element, T)].
23+
24+
delete(Key, [{Key, _Value}|T]) ->
25+
T;
26+
delete(Key, [H|T]) ->
27+
[H|delete(Key, T)];
28+
delete(_Key, []) ->
29+
[].
30+
31+
read(Key, [{Key, Element}|_T]) ->
32+
{ok, Element};
33+
read(_Key, []) ->
34+
{error, instance};
35+
read(Key, [_H|T]) ->
36+
read(Key, T).
37+
38+
match(Element, Db) ->
39+
match_acc(Element, [], Db).
40+
41+
match_acc(Element, Matches, [{Key, Element}|T]) ->
42+
match_acc(Element, [Key|Matches], T);
43+
match_acc(_Element, Matches, []) ->
44+
Matches;
45+
match_acc(Element, Matches, [_H|T]) ->
46+
match_acc(Element, Matches, T).
47+
48+
49+
test_db() ->
50+
Db = new(),
51+
io:fwrite("Db = ~p~n", [Db]),
52+
Db1 = write(francesco, london, Db),
53+
io:fwrite("Db1 = ~p~n", [Db1]),
54+
Db2 = write(lelle, stockholm, Db1),
55+
io:fwrite("Db2 = ~p~n", [Db2]),
56+
Read1 = read(francesco, Db2),
57+
io:fwrite("Read = ~p~n", [Read1]),
58+
Db3 = write(joern, stockholm, Db2),
59+
io:fwrite("Db3 = ~p~n", [Db3]),
60+
Read2 = read(ola, Db3),
61+
io:fwrite("Read2 = ~p~n", [Read2]),
62+
Match1 = match(stockholm, Db3),
63+
io:fwrite("Match1 = ~p~n", [Match1]),
64+
Db4 = delete(lelle, Db3),
65+
io:fwrite("Db4 = ~p~n", [Db4]),
66+
Match2 = match(stockholm, Db4),
67+
io:fwrite("Match2 = ~p~n", [Match2]).

0 commit comments

Comments
 (0)