[erlang-questions] Learning erlang - is this an efficient way to build a list?

graemebe <>
Fri Oct 12 21:13:48 CEST 2007


I've just started learning erlang. I wanted to create a set of processes and
keep their pids in a list and send a message to each with a list
comprehension. In general, is the spawnem function I hacked out below an
efficient way to build a list?

-module(ring).
-export([start/0, recv/0, spawnem/1]).

% Receive a message and print it, repeat.
%
recv() -> 
	receive
		Msg -> io:fwrite("~p\n", [Msg]),
		recv()
	end.

% Spawn some processes and send a message to each.
%
start() ->
	M=10,
	P=ring:spawnem(M),
	[X ! "hello world!" || X <- P].

% Function to Spawn N processes
%
spawnem(N) when is_integer(N), N > 0 -> spawnem_acc(N, [spawn(fun
ring:recv/0)]).
spawnem_acc(N, L) when is_integer(N), N > 1 -> spawnem_acc(N-1, [spawn(fun
ring:recv/0)] ++ L);
spawnem_acc(1, L) -> L.


Any comments/optimisations appreciated!

Cheers,
Graeme.





-- 
View this message in context: http://www.nabble.com/Learning-erlang---is-this-an-efficient-way-to-build-a-list--tf4540288.html#a12958075
Sent from the Erlang Questions mailing list archive at Nabble.com.




More information about the erlang-questions mailing list