[erlang-questions] Circular list
Ulf Wiger (TN/EAB)
Mon Aug 25 15:33:17 CEST 2008
> Doing the below is pretty inefficient, as Programming Erlang by Joe
> Armstrong pg. 64 mentions.
> List ++ [Foo],
> I'm curious why doing this doesn't work at all.
> 4> L3 = [L2|"F"].
The pattern [A|B] means "a list with the element A followed by
the list B".
In this case A = L2 and B = "F". So it *does* work - it's
just doesn't do the same thing as ++. ;-)
Using [Head|Tail] patterns, the Erlang equivalent to ++
'++'([H|T], L2) ->
'++'(, L2) ->
That is, you need to iterate to the end of the first list
in order to append another list to it.
The '++'(A,B) function above is less efficient than A++B,
since the latter is a BIF.
One place where you could use [L1|L2], or even [L1,L2]
in place of append, is when building an "IO list". When
sending a "deep" list through a port, or converting it
to a binary, using list_to_binary/1 or iolist_to_binary/1,
it is automatically and efficiently flattened.
> I'm not too keen on how lists work, so this is puzzling to me :) .
> On Aug 22, 9:34 am, "Colm Dougan" <colm.dou...@REDACTED> wrote:
>> If I have a list of a fixed size (say 10,000 elements). What is the
>> most efficient way to add a new item to the list and force out the old
>> first element. By most efficient I mostly mean without having to copy
>> the entire list each time, if that is even possible.
>> I'm currently doing a double reverse trick, e.g. :
>> Eshell V5.6.3 (abort with ^G)
>> 1> L1 = ["A", "B", "C", "D", "E"].
>> 2> [_ | L2] = L1.
>> 3> lists:reverse(["F" | lists:reverse(L2)]).
>> Is there a more efficient way? I tried a benchmark and the reverse
>> seems more costly than I expected.
>> erlang-questions mailing list
> erlang-questions mailing list
More information about the erlang-questions