So, I just bought “Seven Languages in Seven Weeks”. I’ve read the Ruby chapter, not big deal at all, so I slipt it. I also skip Io, Prolog and Scala (for now), and then, fall in Erlang!

I’ll explain it better another day, but, as you may know, Erlang is a concurrency language, that used to turn difficult thing easy and easy things difficult. There is a price to be paid for solve the world first problems.

World first problems

So, I’ll share with you guys my solutions to the problems proposed by the book.

Day 1

Problem 1

Write a function that uses recursion to return the number of words in a string.

Solution:

list_length([]) -> 0;
list_length(String) ->
  [_ | Tail] = String,
  1 + list_length(Tail).
count_words(Text) ->
  R = re:split(Text, " "),
  list_length(R).

Just a simple pattern matching and a tail recursion in list length, and in count_words we has regex to split the text by space, to actually get the words. Sure, there is simple ways to solve that, but, the fun is to do in a “complicated” way. Erlang already has a function to count words, FYI.

Problem 2

Write a function that uses recursion to count to ten.

count_until(Val, Max) when Val < Max ->
  io:fwrite("~w~n", [Val]),
  count_until(Val + 1, Max);
count_until(_, Max) ->
  io:fwrite("~w~n", [Max]).
count_until(Max) ->
  count_until(0, Max).

Nothing new here. At all.

Problem 3

Write a function that uses matching to selectively print “success” or “error: message” given input in the form {error, Message} or success.

What a easy problem. Take the solution:

print_msg(success) -> io:fwrite("Success~n");
print_msg({error, Message}) ->
  io:fwrite("sir... we got an error: ~s~n", [Message]).

Day 2

Problem 1

Consider a list of keyword-value tuples, such as [{erlang, "a functional language"}, {ruby, "an OO language"}]