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
September 14th, 2010 - 14:02
“case” in match/2 can be omitted:
match(Element, Db) ->
lists:filter(fun({_, E}) -> E =:= Element end, Db).
but original exercise required that match/2 returns list of keys, not list of tuples, so it could look like:
match(Element, Db) ->
MatchedTuples = lists:filter(fun({_, E}) -> E =:= Element end, Db),
element(1, lists:unzip(MatchedTuples)).
But this is rather too complicated. Using list comprehension gives us a simpler version:
match(Element, Db) ->
[Key || {Key, E} <- Db, E =:= Element].
March 8th, 2011 - 18:11
I haven’t made it far enough in the book to use the list comprehension. I saw it when reading through the other book, but wanted to keep with what had been taught so far in this book.