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

YC yinso.chen@REDACTED
Fri Oct 12 22:57:01 CEST 2007


In general what I've seen is to use the cons operator rather than append,
because append is O(n) and cons is O(1), but in your case it's fine as you
are still reversing the list, and hence your append is O(1) as well.  I
guess the key is in reversing the list ;)

On 10/12/07, graemebe <graemebe@REDACTED> wrote:
>
>
> 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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20071012/cc4b31a2/attachment.htm>


More information about the erlang-questions mailing list