I have two dictionaries, and their values incidcate type effectiveness of a Pokémon attack. Now I want to combine these to have the combined effectiveness.
So for instance, one dictionary has:
normal -> 0.5
fire -> 2
The other has:
water-> 0.5
fire -> 2
The combined would be:
normal -> 0.5
water-> 0.5
fire -> 4
I found a function for dict called merge
: https://package.elm-lang.org/packages/elm/core/1.0.2/Dict#merge, but can't figure out how to use it, nor could I find an example.
So, how do you use Dict.merge? Could you provide an example?
You can merge two dictionaries by iterating over the key-value pairs of the second dictionary with the first one.
Dictionaries can also be merged by using the unpacking operator (**). It is a unary operator with a dict object as an operand. It adds each k-v pair in an empty dictionary. Obviously, if the second dictionary is also unpacked, the value of the existing key will be updated.
Dictionary is also iterable, so we can use itertools. chain() to merge two dictionaries. The return type will be itertools.
The signature might be confusing you because it isn't restricted to merging into a new Dict
, but could merge into a list of key-value pairs instead, for example. When reading the signature in your case you can replace result
with Dict comparable c
. or even use Int
in place of both a
, b
and c
.
Edit: For easy reference, the signature is:
merge :
(comparable -> a -> result -> result)
-> (comparable -> a -> b -> result -> result)
-> (comparable -> b -> result -> result)
-> Dict comparable a
-> Dict comparable b
-> result
-> result
When using it, in order to return an new Dict
we have to pass it Dict.empty
as the initial value and insert the values into the dictionary in each function ourselves, like this:
dictA =
Dict.fromList [ ( "normal", 0.5 ), ( "fire", 2 ) ]
dictB =
Dict.fromList [ ( "water", 0.5 ), ( "fire", 2 ) ]
merged =
Dict.merge
(\key a -> Dict.insert key a)
(\key a b -> Dict.insert key (a + b))
(\key b -> Dict.insert key b)
dictA
dictB
Dict.empty
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With