Unless I'm missing something I think this is directly handled by
`Map.new/2` since it can operate on any enumerable. So:
for {key, val} <- map, into: %{} do
{key, val * 2}
end
is equivalent to:
Map.new(map, fn {key, val} -> {key, val * 2})
Which I think is clear and succinct (although I do think that `Map.new/2`
isn't as widely known as it could be). The implementation is based on
:maps.from_list/1:
https://github.com/elixir-lang/elixir/blob/v1.11.3/lib/elixir/lib/map.ex#L172
-Jason
On Tue, Jan 12, 2021 at 11:51 AM [email protected] <[email protected]>
wrote:
> A common task is to iterate over a map performing some operation thereby
> producing a new map. There are some ways to do this in Elixir presently,
> the simplest probably being for...into:
>
> for {key, val} <- map, into: %{} do
> {key, val * 2}
> end
>
> Enum.reduce/3 is also an option. However, Erlang provides a simple
> function to replace the values of a map with maps:map function:
>
> maps:map(fun(Key, Val) -> 2 * Val end, Map)
>
> I think an equivalent of this in Elixir would be very useful either as
> Map.map/2 or Map.transform_values/2 like so:
>
> Map.transform_values(map, fn {_key, val} -> val * 2 end)
>
> I'm interested to hear if the community considers this a worthwhile
> addition!
>
> --
> You received this message because you are subscribed to the Google Groups
> "elixir-lang-core" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/elixir-lang-core/d843c44b-e658-4d71-bb66-00c1e0a21ef7n%40googlegroups.com
> <https://groups.google.com/d/msgid/elixir-lang-core/d843c44b-e658-4d71-bb66-00c1e0a21ef7n%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>
--
You received this message because you are subscribed to the Google Groups
"elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/elixir-lang-core/CAHMz6kxF_JKsWeKkf%3DG-oStYvQtPtAhGud5HLz8esAz4%3DVmJkg%40mail.gmail.com.