[erlang-questions] optimal way to append an element in a list inside a map

Richard A. O'Keefe ok@REDACTED
Wed Aug 30 02:04:00 CEST 2017

On 30/08/17 5:34 AM, Caragea Silviu wrote:

> Having a map where the value of each element is a list :
> #{ 1 => [], 2 => [], ... n => []}
> and you need to append elements in the list for a specific key,

You write "append", and to append an element X to a list L is to
compute L ++ [X] somehow.  But your sample code computes
[X] ++ L (as [X|L]), which already does not copy L, and is not
appending but prepending.

     case Map
       of #{ Key := List } -> Map#{Key := [Value|List]}
        ; _                -> Map#{Key => [Value]}

does what you appear to want in native syntax.  (Tested.)
What performance difference there may be between this and
your example code is a quality-of-implementation issue
discoverable by benchmarking.

To repeat, it doesn't copy List.
But it has to copy Map in order to change it.
Parts of the new Map will share structure with the old one,
but how much and how much of a cost the copying is will be
a quality-of-implementation issue and depends on the number of
keys in the Map.

It would help to know more about the problem you are actually
trying to solve.

BTW "most optimal" is redundant; "optimal" already means "best".

More information about the erlang-questions mailing list