Both of course are valid - they are equivalents in this example. Enum.map/1
is just much simpler here. You use update_in/3
together with Access.all/0
in case you have to update a nested (non-recursive) structure, for example:
defmodule NiceModule do
def apply_function(map_with_nested_list) do
update_in(map_with_nested_list, [:aa, Access.all()], &do_apply_function/1)
end
defp do_apply_function([x, y]) when is_number(x) and is_number(y), do: [x + 3, y + 2]
# Pay attention that apply_function/1 call here was changed to do_apply_function1
defp do_apply_function(sublist) when is_list(sublist), do: do_apply_function(sublist)
defp do_apply_function(other), do: other
end
map = %{
# aa in your example becomes a key in map
aa: [
[2, 5.0 , [ 1 , 1 ]],
[[13.0, 17.0], [25.0, 0.0], [0, 0]] ,
[ 2 ,2 ]
]
}
NiceModule.apply_function(map)
However if in above example we may use the value of a map key as same as sublist, so we can use Map.update!/3
instead.
defmodule NiceModule do
def apply_function(map_with_nested_list) do
Map.update!(map_with_nested_list, :aa, fn
# the difference is that specified map value can be a list with 2 numbers (not nested)
[x, y] when is_number(x) and is_number(y) -> [x + 3, y + 2]
sublist when is_list(sublist) -> apply_function(sublist)
# similar case here - we allow everything else as a map value
other -> other
end)
end
end
but nested data does not need to be that simple (nested list or map with nested list), but be more complex. Simply try to find the API that do what you expect in simplest form.
In your example you did not support root list to not be nested or be something else as the item
variable is the item in the root list and not the root list itself. To do same in my first example we would need to move pattern-matching to apply_function/1
definition, for example:
defmodule NiceModule do
# the difference is that specified map value can be a list with 2 numbers (not nested)
def apply_function([x, y]) when is_number(x) and is_number(y), do: [x + 3, y + 2]
def apply_function(sublist) when is_list(sublist), do: Enum.map(sublist, &apply_function/1)
# similar case here - we allow everything else as a map value
def apply_function(other), do: other
end