micah
micah

Reputation: 8116

List Cons-Into Function?

I am often wanting to take one list and cons every element into an existing list.

MyList = [3,2,1],
MyNewElements = [4,5,6],
MyNewList = lists:foldl(fun(A, B) -> [A | B] end, MyList, MyNewElements).
%% [6,5,4,3,2,1]

Assuming MyList has 1M elements and MyNewElements only has a few, I want to do this efficiently.

I couldn't figure out which of these functions- if any- did what I was trying to do: https://www.erlang.org/doc/man/lists.html

Upvotes: 1

Views: 97

Answers (3)

José M
José M

Reputation: 3509

Another option, aside from those already provided, would be just to have

NewDeepList = [MyList | DeepList]

and modify the reading/traversing to be able to handle [[element()]] instead of [element()].

Upvotes: 3

legoscia
legoscia

Reputation: 41658

Adding a short list to the beginning of a long list is cheap - the execution time of the ++ operator is proportional to the length of the first list. The first list is copied, and the second list is added as the tail without modification.

So in your example, that would be:

lists:reverse(MyNewElements) ++ MyList

(The execution time of lists:reverse/1 is also proportional to the length of the argument.)

Upvotes: 3

Chen Yu
Chen Yu

Reputation: 4077

Because erlang is function language and is different from c, javascript, it copy variable and modify it, not just modify it. Therefore it is impossible compression to o(A).length(A) is length of new added elements.

Upvotes: -1

Related Questions