Thursday, January 03, 2013

Day 1 with Erlang

I started reading Seven Languages in Seven Weeks, which spends a week each on one of seven programming languages selected to teach the reader a new way of thinking.  Each language chapter is separated into separate days with each day ending with a set of homework.
  • Write a function that uses recursion to return the number of words in a string.  
  • Write a function that uses recursion to count to ten.  
  • Write a function that uses matching to selectively print "success" or "error: messsage" given input of the form {error, Message} or success.  
Functions, functions, functions.  Anyway, it took a big of head scratching, but I got the general idea.  
-module(day1).
-export([count_words/1,count_to_num/1,some_response/1]).
-import(string).
-import(io).

% recursion to count number of words in a string
count_words(Word) -> count_list(string:tokens(Word, " ")).

count_list([]) -> 0;
count_list([Foo | Rest]) -> 1 + count_list(Rest).

% recursion to count to a given number
count_to_num(Number) -> counter(1, Number).

counter(I, Number) when I == Number ->
io:put_chars(string:concat(integer_to_list(I), "\n"));
counter(I, Number) ->
io:put_chars(string:concat(integer_to_list(I), "\n")),
counter(I+1,Number).

% message based on input
some_response({error, Message}) -> io:put_chars("error: message\n");
some_response(success) -> io:put_chars("success\n").
I'm exporting three functions to do the three tasks.  count_words takes a string and breaks it up into pieces that is counted by count_words, which just counts the length of the list.  I could have just used the length function, but that wouldn't fulfill the recursive requirement and I was hoping I wouldn't have to do the string parsing myself.  Maybe that's cheating.  

Counting, I assumed, meant printing to the shell and was the easiest to do.  I used another auxiliary function to do keep track of what's been printed out already without having the user supply this, but I guess I could have allowed the user to do this, too.  

The third task was simple pattern matching, where the tuple starting with the atom error would print the error message and the single-arity function would print the success.  Easy.  

Anyway, it was a fun introduction to Erlang and a good challenge for someone who's never seen it before.  I'm looking forward to learning more and seeing what all the fuss is about.  If anyone has any feedback on how I could improve my coding style, I'd appreciate it.