[ Content | View menu ]

Erlang Hack Night

Mark Mzyk | November 2, 2008

I managed to make it out to the Erlang hack night that Kevin Smith had out at Carrboro Creative Coworking recently.  It was a lot of fun.  Kevin rehashed his talk on Erlang that he had also recently given to the Raleigh Ruby Brigade.  As a reminder to him, he needs to fix the slides he has out of order, because I probably won’t be there to heckle him about it the third time he gives the talk.

Since I had already heard the talk, I half listened and went to work trying to solve some of the problems that Kevin had drawn up beforehand.  Kevin had come up with a series of challenges to try and solve in Erlang, each one getting progressively harder (I’ve uploaded the PDF of the problems here, for anyone who is interested).  Since I’m new to Erlang and have only read half of Programming Erlang (what I call the Crosswalk, but no one else does) I opted to start with the first problem:

Write three functions. Each function should satisfy one of the following criteria:

a. Adds two even numbers together
b. Adds two odd numbers together
c. Adds two numbers together

Here is my solution, which I wrote in a module that I creatively called addstuff.  I would have called it add, but I didn’t want it to potentially collide with any other modules.

-export([addeven/2, addodd/2, addnums/2]).
addeven(N,P) when (N rem 2 == 0) and (P rem 2 == 0) -> N + P;
addeven(N,P) -> printmsg(“even”).

addodd(N,P) when (N rem 2 /= 0) and (P rem 2 /= 0) -> N + P;
addodd(N,P) -> printmsg(“odd”).

addnums(N,P) -> N + P.

printmsg(N) -> io:format(“You didn’t give me two ~s nums. ~n”,[N]).

If you have a different answer feel free to post it in the comments.  Based on the expereince from the last time I posted Erlang code, I’ve turned off the preview system since it can’t be relied upon to show how formatted code will be displayed.