Data types in Haskell are also how we express data structures. Thanks to laziness, writing data structures in Haskell can present some interesting opportunities for thinking about new ways to express the structures of data. Most data structures that you’ll build in Haskell are recursive, or as we sometimes call them, inductively defined . In this section, you’ll implement several different inductively defined data structures.
Counting With Peano Numbers
The simplest type of inductively defined data structure that you can implement is a type that represents a peano number . Peano numbers are a way of representing whole numbers as a recursive function, where a given peano number is either “zero” or “a successor to a peano number.” Peano numbers will have some use later on in this book when you learn about writing more advanced programs inside of the type system, but for now we won’t focus on a practical use for them. Instead, they’ll serve as a simple introduction to the idea of inductively defined data structures.
You can implement peano numbers as a sum type with two constructors. We’ll call our data type Peano and we’ll begin by adding a single value constructor. The first constructor we’ll call Z , and it represents zero. It won’t need to have any values associated with it, since it represents the single unit value of zero:
| | data Peano = Z |
The successor constructor, which we’ll call S will have a value, which is the peano number that it’s a successor to:
| | data Peano = Z | S Peano |
With this definition you can write functions like toPeano and fromPeano to walk the inductively defined data structure to get a numeric value. Let’s implement those two functions to start with, so that it’s easy to test with different values:
| | toPeano :: Int -> Peano |
| | toPeano 0 = Z |
| | toPeano n = S (toPeano $ n - 1) |
| | |
| | fromPeano :: Peano -> Int |
| | fromPeano Z = 0 |
| | fromPeano ( S p) = succ (fromPeano p) |
If you look closely, you’ll see that there’s a lot of similarity between the two functions. Both are recursive functions with a base case at zero. The successor functions in both cases reduce their input while growing their output. In toPeano each recursive call adds a new S constructor. In fromPeano we’re using the succ function, from Prelude , which increments an enumeration. In our case we’re using Int values, so succ n is another way of saying n + 1 , but the name in this case serves to illustrate the similarities between the two functions.
You can load these functions up into ghci and play around with them, but it’s hard to do much when you’re limited to just converting back and forth between the different ways of representing a number. Let’s add a couple of functions to make things a little more interesting. We’ll start by adding an equality test for two peano numbers. Although we could of course convert them to Int and compare them with (==) , it will be more illustrative to instead implement equality by traversing the data structure.
To test for equality, we’ll create another recursive function that will traverse our data structure, but in this case we’re taking two parameters, and we’ll want to traverse them at the same time. By definition, Z values are always equal to one another, so we’ll use that as our base case:
| | eqPeano :: Peano -> Peano -> Bool |
| | eqPeano p p' = |
| | case (p,p') of |
| | ( Z , Z ) -> True |
If we have two non-zero values, we can’t directly test them for equality, but we can test whether their predecessors are equal recursively. Since at each step we’re reducing each side by one, if they are equal, the call should terminate at zero for both values at the same time:
| | ( S n, S n') -> eqPeano n n' |
Finally, if one of the values is Z , but not the other, then they are not equal, because Z is only equal to Z . With that change, the full function will look like:
| | eqPeano :: Peano -> Peano -> Bool |
| | eqPeano p p' = |
| | case (p,p') of |
| | ( Z , Z ) -> True |
| | ( S n, S n') -> eqPeano n n' |
| | _ -> False |
Lastly, let’s add a function to add two peano numbers. Try to implement this function yourself as an exercise before continuing on to the solution:
| | addPeano :: Peano -> Peano -> Peano |
| | addPeano Z b = b |
| | addPeano ( S a) b = addPeano a ( S b) |
In this example, we’re recursively destructuring the first parameter and for each successor constructor we remove from the left-hand side, we add one to the right-hand side.
Inductively Defined Lists
The structure of the peano numbers, and the patterns you used for working with them, might have brought to mind the patterns that you’ve used when writing functions that work with lists. In fact, the structure of a linked list in Haskell very closely resembles that of the peano numbers. An inductively defined list will have two constructors, one representing an empty list, and another representing the value of the head of the list, and the tail of the list. One big difference is that for lists, we’ll want to add an additional type parameter so that we can hold any sort of value. Let’s write a linked list implementation to see it in action:
| | data List a = Empty | Cons a ( List a) |
You can implement toList and fromList functions using a similar pattern to the one that you used to implement toPeano and fromPeano . Try to write these functions yourself before you look at the example implementations:
| | toList :: [a] -> List a |
| | toList [] = Empty |
| | toList (x:xs) = Cons x (toList xs) |
| | |
| | fromList :: List a -> [a] |
| | fromList Empty = [] |
| | fromList ( Cons x xs) = x : fromList xs |
Manually implementing recursion on our lists is fine for these two functions, but if you were going to use them to write a longer program, it would start to get frustrating. Let’s try to refactor the recursion out of these implementations and, in the process, look at how we can implement our own higher order functions on top of inductively defined data structures. We’ll start with toList , which we can write using our friend foldr from Prelude :
| | toList :: [a] -> List a |
| | toList = foldr Cons Empty |
Going the other way, writing fromList , the algorithm that we want is the same:
| | fromList :: List a -> [a] |
| | fromList = listFoldr (:) [] |
The problem here is that we haven’t defined a fold function for our custom list type. Let’s write one now. You can try to implementing this yourself before you look at the example:
| | listFoldr :: (a -> b -> b) -> b -> List a -> b |
| | listFoldr _ b Empty = b |
| | listFoldr f b ( Cons x xs) = |
| | f x $ listFoldr f b xs |
You can see in your implementation of the fold function, just like when you were working with peano numbers or manually implementing your list conversion functions, that the structure of the functions matches the structure of the recursion in the data types. This is a pattern that you’ll see repeated across many different data structures as you work with Haskell applications.
For the sake of completeness, try implementing the following functions based on their type signatures and the behavior of the list functions in Prelude :
| | listFoldl :: (b -> a -> b) -> b -> List a -> b |
| | listHead :: List a -> Maybe a |
| | listTail :: List a -> List a |
| | listReverse :: List a -> List a |
| | listMap :: (a -> b) -> List a -> List b |