[erlang-questions] Learning erlang - is this an efficient way to build a list?
David Mercer
dmercer@REDACTED
Fri Oct 12 21:42:17 CEST 2007
You are building the list in reverse order, which is efficient. I would
typically prepend element X to list L with the syntax [X|L] rather than
[X]++L, but I'm not sure which is more efficient.
Cheers,
David
-----Original Message-----
From: erlang-questions-bounces@REDACTED
[mailto:erlang-questions-bounces@REDACTED] On Behalf Of graemebe
Sent: Friday, October 12, 2007 14:14
To: erlang-questions@REDACTED
Subject: [erlang-questions] Learning erlang - is this an efficient way to
build a list?
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.
_______________________________________________
erlang-questions mailing list
erlang-questions@REDACTED
http://www.erlang.org/mailman/listinfo/erlang-questions
More information about the erlang-questions
mailing list