Search code examples
dictionaryelm

Elm: How to merge two dictionaries?


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?


Solution

  • 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