Erlang Programming Exercise: 3-7
For this exercise we get to rewrite Exercise 3-4 using the lists module. The author asks us how much shorter the newer version is from the first version. My old version is 39 lines long while my new version is 30 lines. It's a nice savings, but I was hoping for more. The change that I like the most, is that I don't have any a recursion. I can see at a glace what the functions are doing now.
-module(threeseven).
-export([new/0, destroy/1, write/3, delete/2, read/2, match/2]).
new() ->
[].
destroy(_Db) ->
ok.
delete(Key, Db) ->
lists:keydelete(Key, 1, Db).
write(Key, Element, Db) ->
NewDb = delete(Key, Db),
[{Key, Element}|NewDb].
read(Key, List) ->
case lists:keyfind(Key, 1, List) of
false -> {error, instance};
{Key, Value} -> {ok, Value}
end.
match(Element, Db) ->
Matcher = fun(Elem) ->
case Elem of
{_Key,Element} -> true;
_Other -> false
end
end,
lists:filter(Matcher, Db).
It took me a while to get the syntax for the case statement and the fun. I found it confusing why I didn't need any punctuation after the last case statement or the end token.
I think it's important to point out how valuable the erlang man pages are. I was able to find the information I needed about the lists module by running this at the command line:
erl -man lists
It gives you a nice bit of documentation about the lists module.
Cheers,
-Halzy