Map.transform_values

49 views
Skip to first unread message

Marc-André Lafortune

unread,
Jan 13, 2022, 12:55:24 PM1/13/22
to elixir-lang-core
I somehow missed both the conversation to introduce `Map.map` and that about deprecating it... 🤔

What I tend to use a lot is applying a 1-arity function to all values:

```
Map.new(my_map, fn {key, value} -> {key, do_something(value)} end)
```

Probably because I come from Ruby, I miss `transform_values`, both for its conciseness and it's expressivity. It makes it clear that the result will be a map with the same keys.

The example above could be written using two short forms that were not available:
```
Map.new(my_map, fn {key, value} -> {key, do_something(value)} end)
# Makes it possible to inline an expression with &(...&1...):
Map.transform_values(my_map, &do_something(&1))
# or if transform is actually a function:
Map.transform_values(my_map, &do_something\1)
```

From an efficiency point of view, `Maps.transform_values` can use `maps:map`, which will be more efficient (I presume avoids all key comparisons, for small maps reuses the list of keys, for large maps avoids rehashing, comparing and organizing the keys)

For completedness sake, I'd propose `Map.transform_keys` which I also use, although less often. It has no performance advantage, but remains clear in its intent.

Marc-André Lafortune

unread,
Jan 13, 2022, 10:00:58 PM1/13/22
to elixir-lang-core
After checking the source, it appears I was presuming wrong, as `:maps.map` is not currently optimized like it could be (PR to come one day 😅)
Reply all
Reply to author
Forward
0 new messages