elm-community/dict-extra/1.4.0

NOTE: this package is not compatible with Elm 0.19.1

Dict.Extra

Convenience functions for working with Dict

List operations

groupBy : (a -> comparable) -> List a -> Dict comparable (List a)

Takes a key-fn and a list. Creates a Dict which maps the key to a list of matching elements.

mary = {id=1, name="Mary"}
jack = {id=2, name="Jack"}
jill = {id=1, name="Jill"}
groupBy .id [mary, jack, jill] == Dict.fromList [(1, [mary, jill]), (2, [jack])]
fromListBy : (a -> comparable) -> List a -> Dict comparable a

Create a dictionary from a list of values, by passing a function that can get a key from any such value. If the function does not return unique keys, earlier values are discarded. This can, for instance, be useful when constructing Dicts from a List of records with id fields:

mary = {id=1, name="Mary"}
jack = {id=2, name="Jack"}
jill = {id=1, name="Jill"}
fromListBy .id [mary, jack, jill] == Dict.fromList [(1, jack), (2, jill)]

Manipulation

removeWhen : (comparable -> v -> Bool) -> Dict comparable v -> Dict comparable v

Remove elements which satisfies the predicate.

dict = Dict.fromList [("Mary", 1), ("Jack", 2), ("Jill", 1)]
removeWhen (\_ v -> v == 1) dict == Dict.fromList [("Jack", 2)]
removeMany : Set comparable -> Dict comparable v -> Dict comparable v

Remove a key-value pair if its key appears in the set.

dict = Dict.fromList [("Mary", 1), ("Jack", 2), ("Jill", 1)]
removeMany (Set.fromList ["Mary", "Jill"]) dict == Dict.fromList [("Jack", 2)]
keepOnly : Set comparable -> Dict comparable v -> Dict comparable v

Keep a key-value pair if its key appears in the set.

dict = Dict.fromList [("Mary", 1), ("Jack", 2), ("Jill", 1)]
removeMany (Set.fromList ["Jack"]) dict == Dict.fromList [("Jack", 2)]
mapKeys : (comparable -> comparable) -> Dict comparable v -> Dict comparable v

Apply a function to all keys in a dictionary.

mapKeys ((+) 1) (Dict.fromList [(5, "Jack"), (10, "Jill")])
== Dict.fromList [(6, "Jack"), (11, "Jill")]
filterMap : (comparable -> a -> Maybe b) -> Dict comparable a -> Dict comparable b

Apply a function that may or may not succeed to all entries in a dictionary, but only keep the successes.

isTeen : Int -> String -> Maybe String
isTeen n a =
    if 13 <= n && n <= 19 then
        Just <| String.toUpper a
    else
        Nothing


Dict.fromList
    [ ( 5, "Jack" )
    , ( 15, "Jill" )
    , ( 20, "Jones" )
    ]
    |> filterMap isTeen
    == Dict.singleton 15 "JILL"
invert : Dict comparable1 comparable2 -> Dict comparable2 comparable1

Inverts the keys and values of an array.

dict = Dict.fromList [("Jill", 5), ("Jack", 10)]
inverted = Dict.fromList [(5, "Jill"), ("Jack", 10)]
Dict.invert dict == inverted