# Enum.reduce issue

I have a map with the following

total = %{"usd" => 0, "euro" => 0}

And I have an a list of maps like this:

movements = [%{iso: "usd", sum_total: 10, special: true}, %{iso: "usd", sum_total: 5, special: false}, %{iso: "euro", sum_total: 15, special: false}]

Enum.reduce movements, total, fn(mov, total_acc) ->
if mov[:special] do
# some code goes here
# this function returns a map
some_function(total_acc, mov, some_var)
else
# some code goes here
# this function returns a map to
some_other_function(total_acc, mov, some_other_var)
end
end

My problem is that my reduce always return the total map with the empty values (total = %{â€śusdâ€ť => 0, â€śeuroâ€ť => 0}), nothing is updated.

Your problem might be with the functions some_function/3 and some_other_function/3 and not Enum.reduce/3 itself. My guess would be that they donâ€™t return the updated total.

total = %{}

movements = [
%{iso: "usd", sum_total: 10, special: true},
%{iso: "usd", sum_total: 5, special: false},
%{iso: "euro", sum_total: 15, special: false}
]

some_function = fn
total, %{iso: currency, sum_total: sum_total, special: true}, _some_var ->
change = sum_total - 5 # because `special`
Map.update(total, currency, change, &(&1 + change))
total, %{iso: currency, sum_total: sum_total, special: false}, _some_var ->
Map.update(total, currency, sum_total, &(&1 + sum_total))
end

Enum.reduce(movements, total, fn movement, total ->
some_function.(total, movement, nil)
end)

# returns %{"euro" => 15, "usd" => 10}
1 Like