Haskell/Other data structures

In this chapter, we will work through examples of how the techniques we have studied thus far can be used to deal with more complex data types. In particular, we will see examples of recursive data structures, which are data types that can contain values of the same type. Recursive data structures play a vital role in many programming techniques, and so even if you are not going to need defining a new one often (as opposed to using the ones available from the libraries) it is important to be aware of what they are and how they can be manipulated. Besides that, following closely the implementations in this chapter is a good exercise for your budding Haskell abilities.

Trees
One of the most important types of recursive data structures is trees. There are several different kinds of trees, so we will arbitrarily choose a simple one to use as an example. Here is its definition:

As you can see, it's parameterized; i.e. we can have trees of s, trees of  s, trees of  s, trees of   pairs and so forth. What makes this data type special is that  appears in the definition of itself. A  is either a leaf, containing a value of type   or a branch, from which hang two other trees of type.

Lists as Trees
As we have seen in Lists II and Lists III, we break lists down into two cases: An empty list (denoted by []), and an element of the specified type plus another list (denoted by (x:xs)). That means the definition of the list data type might look like this:

An equivalent definition you can actually play with is:

Like trees, lists are also recursive. For lists, the constructor functions are  and. They correspond to  and   in the   definition above. That implies we can use  and   for pattern matching just as we did with the empty list and the.

Maps and Folds
We already know about maps and folds for lists. Now, we can write map and fold functions for our new  type. To recap:

Map
Let's take a look at the definition of  for lists:

If we were to write, what would its type be? Defining the function is easier if you have an idea of what its type should be.

We want  to work on a   of some type and return another   of some type by applying a function on each element of the tree.

This is just like the list example.

Now, when talking about a, each   only contains a single value, so all we have to do is apply the given function to that value and then return a   with the altered value:

This looks a lot like the empty list case with. Now, if we have a, it will include two subtrees; what do we do with those? The list- uses a call to itself on the tail of the list (recursion), so we also shall do that with the two subtrees. The complete definition of  is as follows:

We can make this a bit more readable by noting that  is itself a function with type. This gives us the following revised definition:

If you didn't follow that immediately, try re-reading it. This use of pattern matching may seem weird at first, but it is essential to the use of datatypes. Remember that pattern matching happens on constructor functions.

When you're ready, read on for folds over Trees.

Fold
As with map, let's first review the definition of  for lists:

Recall that lists have two constructors:

Thus  takes two arguments corresponding to the two constructors:

Let's take a moment to make this clear. If the initial  is given an empty list, then the default accumulator is returned. With a non-empty list, the first element is combined (with ) with the result of folding the tail of the list, and so the fold proceeds until we get to the empty list.

Like  for lists, we want   to transform a tree of some type into a value of some other type; so in place of  we will have. How do we specify the transformation? First note that has two constructors (just like lists have two constructors):

So  will have two arguments corresponding to the two constructors:

Putting it all together we get the following type definition:

That is, the first argument, of type, is a function specifying how to combine subtrees into a single result; the second argument, of type , is a function specifying what to do with leaves (which are the end of recursion, just like empty-list for lists); and the third argument, of type , is the whole tree we want to fold.

As with, we'll avoid repeating the arguments   and   by introducing a local function  :

The argument  tells us what to do with   subtrees:

The argument  tells us how to combine the results of "folding" two subtrees:

Our full definition becomes:

For examples of how these work, copy the  data definition and the   and   functions to a Haskell file, along with the following example Tree and example functions to fold over.

Then load it into GHCi and evaluate:

doubleTree tree1 sumTree tree1

Other datatypes
Map and fold functions can be defined for any kind of data type. In order to generalize the strategy applied for lists and trees, in this final section we will work out a map and a fold for a very strange, contrived datatype:

It can be a useful exercise to write the functions as you follow the examples, trying to keep the coding one step ahead of your reading.

General Map
The first important difference in working with this  type is that it has two type parameters. For that reason, we will want the map function to take two functions as arguments, one to be applied on the elements of type a and another for the elements of type b. With that accounted for, we can write the type signature of :

Next step is defining. The key point is that maps preserve the structure of a datatype, so the function must evaluate to a  which uses the same constructor as the one used for the original. For that reason, we need one definition to handle each constructor, and these constructors are used as patterns for writing them. As before, to avoid repeating the  argument list over and over again a where clause comes in handy. A sketch of the function is below:

The first two cases are fairly straightforward, as there is just a single element of  or   type inside the.

is trickier because it contains a list whose elements are themselves data structures (the tuples). So we need to navigate the nested data structures, apply  and   on all elements of type   and   and eventually (as a map must preserve structure) produce a list of tuples –   – to be used with the constructor. The simplest approach might seem to be just breaking down the list inside the  and playing with the patterns:

This appears to be written as a typical recursive function for lists. We start by applying the functions of interest to the first element in order to obtain the head of the new list,. But what will we cons it to? As  requires a   argument, we need to make a   using the list tail in order to make the recursive call. But then  will give a   and not a list, so we have to retrieve the modified list from that – that's the role of the lambda function. Finally, there is also the empty list base case to be defined as well.

After all of that, we are left with a messy function. Every recursive call of  requires wrapping   into a , while what we really wanted to do was to build a list with  and the modified. The problem with this solution is that  can (thanks to pattern matching) act directly on the list head but (due to its type signature) can't be called directly on the list tail. For that reason, it would be better to apply  and   without breaking down the list with pattern matching (as far as   is directly concerned, at least). But there was a way to directly modify a list element-by-element...

...our good old  function, which modifies all tuples in the list   using a lambda function. In fact, the first attempt at writing the definition looked just like an application of the list map except for the spurious  packing and unpacking. We got rid of these by having the pattern splitting of  done by , which works directly with regular lists. You could find it useful to expand the map definition inside  to see the difference more clearly. Finally, you may prefer to write this new version in an alternative and clean way using list comprehension syntax:

Adding the  function, we only have the   left to define:

All we need to do is apply  recursively:

General Fold
While we were able to define a map by specifying as arguments a function for every separate type, this isn't enough for a fold. For a fold, we'll need a function for every constructor function. With lists, the constructors are  and. The  argument in the   function corresponds to the   constructor. The  argument in the   function corresponds to the   constructor. The  datatype has four constructors, so we need four functions – one for handling the internal structure of the datatype specified by each constructor. Next, we have an argument of the  type, and finally we want the whole fold function to evaluate to a value of some other, arbitrary, type. Additionally, each individual function we pass to  must evaluate to the same type   does. That allows us to make a mock type signature and sketch the definition:

Now, we need to figure out which types,  ,   and   correspond to. That is done by analyzing the constructors, since the functions must take as arguments the elements of the datatype (whose types are specified by the constructor type signature). Again, the types and definitions of the first two functions are easy enough. The third one isn't too difficult either because, for the purposes of folding the list of, tuples are no different from a simple type (unlike in the map example, the internal structure does not concern us now). The fourth constructor, however, is recursive, and we have to be careful. As with, we also need to recursively call the   function. This brings us to the final definition:

Folds on recursive datatypes
As far as folds are concerned,  was a fairly nice datatype to deal with. Just one recursive constructor, which isn't even nested inside other structures. What would happen if we added a truly complicated fifth constructor?

This is a valid and yet tricky question. In general, the following rules apply:


 * A function to be supplied to a fold has the same number of arguments as the corresponding constructor.
 * The type of the arguments of such a function match the types of the constructor arguments, except if the constructor is recursive (that is, takes an argument of its own type).
 * If a constructor is recursive, any recursive argument of the constructor will correspond to an argument of the type the fold evaluates to.
 * If a constructor is recursive, the complete fold function should be (recursively) applied to the recursive constructor arguments.
 * If a recursive element appears inside another data structure, the appropriate map function for that data structure should be used to apply the fold function to it.

So  would have the type:

as the type of  is:

The definition of  for the   constructor will be:

Note that nothing strange happens with the  part. No  gets called. What's up? This is recursion, right? Well, not really. and  are different types, so it isn't a real recursion. It isn't guaranteed that, for example,  will work with something of type 'a', where it expects a type 'b'. It can be true for some cases but is not reliable for every case.

Also look at the definition of. Verify that it is indeed a map function as:


 * It preserves structure.
 * Only types are changed.

A nice sounding word
The folds we have defined here are examples of catamorphisms. A catamorphism is a general way to collapse a data structure into a single value. There is deep theory associated with catamorphisms and related recursion schemes; however, we won't go through any of it now, as our main goal here was exercising the mechanics of data structure manipulation in Haskell with believable examples.