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

Bjorn Gustavsson bjorn@REDACTED
Sat Oct 13 08:02:33 CEST 2007


YC <yinso.chen@REDACTED> writes:

> 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 ;)

Yes, the important thing is to build the list in reverse order. '++' is fine
as long as the accumulator argument is to the right.

In this simple case, the compiler will itself rewrite

[spawn(fun ring:recv/0)] ++ L

to

[spawn(fun ring:recv/0)|L]

so the cost is exactly the same.

/Bjorn
-- 
Björn Gustavsson, Erlang/OTP, Ericsson AB



More information about the erlang-questions mailing list