Seven Languages in Seven Weeks Part 8: Erlang Day 1
by Justin Michalicek on April 29, 2011, 6:26 a.m. UTCI think I hate Erlang. Sure, it has cool features and nctionality, but this Prolog based syntax is terrible. I would never want to work on a large project using this. I think for real work I'll stick with these OO based languages that mix in functional features where it makes sense.
On to the exercises. First, a function that calls itself recursively to count to 10.
-module(count). -export([counter/0, counter/1]). counter() -> count:counter(1). counter(N) -> if N < 10 -> io:format("~p ",[N]), count:counter(N+1); true -> N end.
Next, a function to display either an error message or success based on the parameters passed in. I did this two ways. First there's the way that is in line with what the book showed for the parameters passed in with error and Message in a tuple together.
-module(error). -export([display_message/1]). display_message(Msg) -> case Msg of success -> "Success"; {error, Message} -> string:concat("Error: ", Message) end.
Next is the same deal, but error and Message get passed as two separate parameters. This does not 100% match what the book said to pass in, but is in line with what was actually covered in day 1.
-module(error2). -export([display_message/1,display_message/2]). display_message(success) -> "Success". display_message(error, Msg) -> string:concat("Error: ", Msg).
The last exercise (the first listed), I actually could not pull off. I was on the right track, but syntax issues and questionable error messages caused me to give up. The goal was to write a recursive function to count the words in a string. My plan was to have a version of the function that took a single parameter, the string, and then another version that took the string and a counter. I would then treat the string like a list and split it into head and tail, if head is a space then increment the counter, then call the function again. But this broke on me when I had an empty string at the end. I could not get Erlang to accept a second word_count/2 function that let me pass in the empty list and counter, it would complain that I had 2 word_count/2 functions.
This issue with complaining about to word_count/2 functions is what broke me. I gave up and checked google. I found a solution that used two function/2 type functions to do it and it compiles, so it was just the way I tried to have two function/2 functions that was wrong, not that you can't do it at all. Annoying. The solution I found was still not satisfactory to me as you had to pass in the initial count of 1 with your string. I found another one that did it with two functions, one function/1 and one function/3 which seemed to work, but I was having trouble parsing the code to understand exactly what was going on.