Bad argument in arithmetic expression

Hey, there!

when run my code i have this error in my display

foods = Map.put(foods, food_name, foods[food_name] + 1)

error: ’ bad argument in arithmetic expression ’

someone know why?

Hello and welcome,

I guess You are passing nil + 1, and that does not work.

You should look for Map.update instead.

BTW You could show the full error stack.

2 Likes

food_name may not be present in the foods map, and then it will return nil. You cannot add atom and integer.

2 Likes

Map.update syntax is a little bit more complex, but solve what You are trying to do.

foods = Map.update(foods, food_name, 1, & &1 + 1)

This is also possible

foods = Map.put(foods, food_name, (foods[food_name] || 0) + 1)
2 Likes
  defp sum_values([id, food_name, price], %{"foods" => foods, "users" => users} = report) do
    users = Map.put(users, id, users[id] + price)
    foods = Map.put(foods, food_name, foods[food_name] + 1)

    %{report | "users" => users, "foods" => foods}
  end