Alright, day 2 of Erlang is done. I have not done the bonus problem yet and I probably won't unless a good idea strikes me.

Day 2 focused on list functionality like foreach, map, folds, etc. as has already been seen with the other languages. It also threw in list comprehensions which mostly feel like maybe a slightly shorter way to write out a map in certain cases. The book does mention that there's a lot more functionality with list comprehensions that was not covered, so maybe they would seem more special if I worked with the extra stuff. Python and Scala also have list comprehensions, so I'll probably use those to learn more about them.

Time for the exercises. The first was to write a function that takes a list of two element tuples to be treated as key/value pairs and the key you'd like to find and then return the value for that key. Since this is a list and not a set, there could be duplicate keys, so I chose to return a list of values. I also put in commented code for assuming only one value (or just returning the first match). I used lists:filter with a closure to find the matches and then a list comprehension to return only the values and not the keys.

-module(hashmap).
-export([get_value/2]).

get_value(L, Name) ->
    Matcher = fun({Key, _}) ->
                      if
                          Key == Name ->
                              true;
                          Key /= Name ->
                              false
                      end
              end,
    [Value || {_, Value} <- lists:filter(Matcher, L)].

    % To return a plain old scalar use below
    % but what if multiple keys match?
    %[Head | Rest] = lists:filter(Matcher, L),
    %{Key, Val} = Head,
    %Val.

The next exercise was to write a list comprehension which takes a list of tuples of {Item, quantity, price} and return a list of {Item, total_price}. There really wasn't much to this one, so here it is. I didn't create a file for this, I just copied the output from erl. As a side note, don't use decimals/floats like below in a real application dealing with money.

Erlang R14A (erts-5.8) [source] [rq:1] [async-threads:0] [kernel-poll:false]

Eshell V5.8  (abort with ^G)
1> Vals = [{"Beer",12,1.99},{"Whiskey",2,30.00},{"Chips",1,2.99}].
[{"Beer",12,1.99},{"Whiskey",2,30.0},{"Chips",1,2.99}]
2> [{Item, Price * Total} || {Item, Total, Price} <- Vals].
[{"Beer",23.88},{"Whiskey",60.0},{"Chips",2.99}]

The "bonus" exercise which I did not do is to write a program that reads a tic-tac-toe board as a list or tuple of 9 elements and determine who won or if it was a tie or if there's just no winner yet. As I said, I haven't done this and likely won't. The logic should basically be the same as the tic-tac-toe game in Scala since that was done using functional style list manipulation. I don't feel like fighting with Erlang syntax to implement duplicate logic. If I think of something that feels different than the Scala logic I'll come back and do this.