Chapter 13. Data Structures
Association Lists
Often, we have to deal with data that is unordered but is indexed by a key. For instance, a Unix administrator might have a list of numeric UIDs (user IDs) and the textual usernames that they correspond to. The value of this list lies in being able to look up a textual username for a given UID, not in the order of the data. In other words, the UID is a key into a database.
In Haskell, there are several ways to
handle data that is structured in this way. The two most common are
association lists and the Map type provided by Data.Map
module. Association lists are handy
because they are simple. They are standard Haskell lists, so all the
familiar list functions work with them. However, for large data sets,
Map will have a considerable performance advantage over
association lists. We’ll use both in this chapter.
An association list is just a normal list containing (key,
value) tuples. The type of a list of mappings from UID to username might
be [(Integer, String)]
. We could use
just about any type[33] for both the key and the value.
We can build association lists just like
we do any other list. Haskell comes with one built-in function called
Data.List.lookup
to look up data in an association list. Its type is Eq a => a -> [(a, b)] ->
Maybe b
. Can you guess how it works from that type? Let’s take
a look in ghci:
ghci>
let al = [(1, "one"), (2, "two"), (3, "three"), (4, "four")]
ghci>
lookup 1 al
Just "one"ghci>
lookup 5 al
Nothing
The lookup
Get Real World Haskell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.