How to add two maps or structs?

I have two maps.
mine = %{a: 1, b:1}
yours = %{a: 1, b: 1, c: 1}

and, I need ours like:
ours = mine + yours = %{a: 2, b: 2, c: 1}

Thank you in advance…

iex(1)> a = %{a: 1, b: 1}
%{a: 1, b: 1}

iex(2)> b = %{a: 1, b: 1, c: 1}
%{a: 1, b: 1, c: 1}

iex(3)> Map.merge(a, b, fn _, v1, v2 -> v1 + v2 end)
%{a: 2, b: 2, c: 1}

Map.merge/3 provides a really nice way to handle this - the function passed as the third argument is called when both maps have an entry for a key and receives three arguments (the key, the value from the first map, the value from the second map).

More-general tools like Enum.reduce can do this as well, if you’re looking for an exercise to practice writing those :slight_smile:

6 Likes