Benjamin Halsted // [bgh] todo, add something clever here.

22Apr/100

Erlang Programming Exercise: 4-1

I'm glad to be past chapter 3, and that I took the time to go through the exercises. I would highly suggest to anybody learning Erlang to do the same. They helped me learn the syntax of the language and to become much more comfortable in Erlang. I also found the erlang man pages to be very helpful. For example, to get the full documentation for the lists module you type "erl -man lists" in a shell.

Before jumping into the exercises for chapter four I went back and re-read the chapter. It's a nice reminder of how Erlang is different from the languages I use for work. I'm still having trouble trying to grok the activity vs task mentality, it's so different from what I'm used to.

Exercise 4-1 I found to be much easier than 3-10. The goal is to start up a process that prints out messages you send to it, but to have the interaction with that process through a public interface.

Here is the interface you are supposed to maintain:

echo:start() ⇒ ok
echo:print(Term) ⇒ ok
echo:stop() ⇒ ok

Since I've been naming my modules after the exercise chapter and number I changed 'echo' to four_one. Here is my solution:

-module(four_one).
-export([start/0,print/1,stop/0]).

-export([loop/0]).

start() ->
	Pid = spawn(four_one,loop,[]),
	register(four_one, Pid),
	ok.

print(Term) ->
	four_one ! {print, Term},
	ok.

stop() ->
	four_one ! stop,
	ok.

loop() ->
	receive
		stop -> ok;
		{print, Term} ->
			io:format("~p~n", [Term]),
			loop()
	end.

Cheers,
Halzy

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Reddit
  • Twitter
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.