Elm Language Collecting Data: Tuples, Records and Dictionaries Dictionaries


Example

Dictionaries are implemented in a Dict core library.

A dictionary mapping unique keys to values. The keys can be any comparable type. This includes Int, Float, Time, Char, String, and tuples or lists of comparable types.

Insert, remove, and query operations all take O(log n) time.

Unlike Tuples and Records, Dictionaries can change their structure, in other words it is possible to add and remove keys.

It is possible to update a value by a key.

It is also possible to access or update a value using dynamic keys.

Accessing values

You can retrieve a value from a Dictionary by using a Dict.get function.

Type definition of Dict.get:

get : comparable -> Dict comparable v -> Maybe v

It will always return Maybe v, because it is possible to try to get a value by an non-existent key.

import Dict

initialUsers =
      Dict.fromList [ (1, "John"), (2, "Brad") ]

getUserName id =
  initialUsers
  |> Dict.get id
  |> Maybe.withDefault "Anonymous"
  
getUserName 2 -- "Brad"
getUserName 0 -- "Anonymous"

Updating values

Update operation on a Dictionary is performed by using Maybe.map, since the requested key might be absent.

import Dict

initialUsers =
  Dict.fromList [ (1, "John"), (2, "Brad") ]

updatedUsers =
  Dict.update 1 (Maybe.map (\name -> name ++ " Johnson")) initialUsers

Maybe.withDefault "No user" (Dict.get 1 updatedUsers) -- "John Johnson"