Search code examples
erlang

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


Solution

  • 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.)