[erlang-questions] optimal way to append an element in a list inside a map
Brujo Benavides
elbrujohalcon@REDACTED
Tue Aug 29 20:29:48 CEST 2017
I think this might be what you are looking for:
append(Key, Value, Map) ->
maps:update_with(Key, fun(Tail) -> [Value | Tail] end, [], Map).
Brujo Benavides <http://about.me/elbrujohalcon>
> On Aug 29, 2017, at 15:19, Dmitry Kolesnikov <dmkolesnikov@REDACTED> wrote:
>
> Hello,
>
> Premature optimisation is an evil ;-)
>
> I would use the following syntax:
> ```
> append(Key, Value, Map) ->
> List = case Map of
> #{Key := Tail} ->
> [Value | Tail];
> _ ->
> [Value]
> end,
> Map#{Key => List}.
> ```
>
> Lists are not copied they are referenced. Maps… Hmm, I am not sure. I hope the implementation is smart enough to keep reference as well.
>
> - Dmitry
>
>
>> On 29 Aug 2017, at 20.34, Caragea Silviu <silviu.cpp@REDACTED> wrote:
>>
>> Hello,
>>
>> Having a map where the value of each element it's a list :
>>
>> #{ 1 => [], 2 => [], ... n => []}
>>
>> and you need to append elements in the list for a specific key, what's the most optimal way to do this without copying the lists and the map inside the VM lot of times ?
>>
>> Anything better than the following solution:
>>
>> append_element(Key, Value, Map) ->
>> case maps:find(Key, Map) of
>> {ok, V} ->
>> maps:put(Key, [Value | V], Map);
>> _ ->
>> maps:put(Key, [Value], Map)
>> end.
>>
>> Kind regards,
>> Silviu
>> _______________________________________________
>> erlang-questions mailing list
>> erlang-questions@REDACTED
>> http://erlang.org/mailman/listinfo/erlang-questions
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20170829/d01f5d10/attachment.htm>
More information about the erlang-questions
mailing list