Chapter 15. Programming with Monads

Golfing Practice: Association Lists

Web clients and servers often pass information around as a simple textual list of key-value pairs:

name=Attila+%42The+Hun%42&occupation=Khan

The encoding is named application/x-www-form-urlencoded, and it’s easy to understand. Each key-value pair is separated by an & character. Within a pair, a key is a series of characters, followed by an =, followed by a value.

We can obviously represent a key as a String, but the HTTP specification is not clear about whether a key must be followed by a value. We can capture this ambiguity by representing a value as a Maybe String. If we use Nothing for a value, then there is no value present. If we wrap a string in Just, then there is a value. Using Maybe lets us distinguish between no value and “empty value.”

Haskell programmers use the name association list for the type [(a, b)], where we can think of each element as an association between a key and a value. The name originates in the Lisp community, where it’s usually abbreviated as an alist. We could thus represent the preceding string as the following Haskell value:

-- file: ch15/MovieReview.hs
    [("name",       Just "Attila \"The Hun\""),
     ("occupation", Just "Khan")]

In Parsing a URL-Encoded Query String, we’ll parse an application/x-www-form-urlencoded string, and we will represent the result as an alist of [(String, Maybe String)]. Let’s say we want to use one of these alists to fill out a data structure:

-- file: ch15/MovieReview.hs ...

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.