Typeable and Data in Haskell

Data.Typeable and Data.Data are rather mysterious. Starting out as a Haskell newbie you see them once in a while and wonder what use they are. Their Haddock pages are pretty opaque and scary in places. Here’s a quick rundown I thought I’d write to get people up to speed nice and quick so that they can start using it.

It’s really rather beautiful as a way to do generic programming in Haskell. The general approach is that you don’t know what data types are being given to you, but you want to work upon them almost as if you did. The technique is simple when broken down.

Requirements

First, there is a class exported by each module. The class Typeable and the class Data . Your data types have to be instances of these if you want to use the generic programming methods on them.

Happily, we don’t have to write these instances ourselves (and in GHC 7.8 it is actually not possible to do so): GHC provides the extension DeriveDataTypeable , which you can enable by adding {-# LANGUAGE DeriveDataTypeable #-} to the top of your file, or providing -XDeriveDataTypeable to ghc .

Now you can derive instances of both:

Now we can start doing generic operations upon X .

The Typeable class

As a simple starter, we can trivially print the type of any instance of Typeable . What are some existing instances of Typeable ? Let’s ask GHCi:

That’s the basic Prelude types and the Typeable library’s own types.

There’s only one method in the Typeable class:

The TypeRep value has some useful normal instances:

Use-case 1: Print the type of something

So we can use this function on a Char value, for example, and GHCi can print it:

This is mostly useful for debugging, but can also be useful when writing generic encoders or any tool which needs an identifier to be associated with some generic value.

Use-case 2: Compare the types of two things

We can also compare two type representations:

Any code which needs to allow any old type to be passed into it, but which has some interest in sometimes enforcing or triggering on a specific type can use this to compare them.

Use-case 3: Reifying from generic to concrete

A common thing to need to do is when given a generic value, is to sometimes, if the type is right, actually work with the value as the concrete type, not a polymorphic type. For example, a printing function:

The specification for this function is: if given an Char , return its string representation, otherwise, return "unknown" . To do this, we need a function that will convert from a polymorphic value to a concrete one:

This function from Data.Typeable will do just that. Now we can implement char :

The Data class

That’s more or less where the interesting practical applications of the Typeable class ends. But it becomes more interesting once you have that, the Data class can take advantage of it. The Data class is much more interesting. The point is to be able to look into a data type’s constructors, its fields and traverse across or fold over them. Let’s take a look at the class.

Again, there are some basic instances provided:

It’s a rather big class, so I’ll just cover some methods that demonstrate the key use-cases.

Use-case 1: Get the data type

Similar to the TypeRep , you can use dataTypeOf to get a unique representation of a data type:

For example:

There aren’t any other interesting instances for this type, but we’ll look at uses for this type later. Representations (so-called FooRep ) tend to be references from which you can reify into more concrete values.

Use-case 2: Inspecting a data type

The most common thing to want to do is to get a list of constructors that a type contains. So, the Maybe type contains two.

We’ll look at what we can do with constructors later.

It’s also surprisingly common to want to see what the constructor is at a particular index. We could write this function ourself, but there’s already one provided:

Sometimes you want to know whether a data type is algebraic (in other words, does it have constructors and is it not one of the built-in types like Int/Float/etc)?

Use-case 3: Get the constructor of a value

We have the method

Which given any instance of Data will yield a constructor.

You can’t do much with a constructor as-is, but compare and print it:

However, those operations by themselves can be useful.

By the way, we can also get back the DataRep of a constructor:

Use-case 4: Get fields of a constructor

Another typical thing to want to do is to use the field names of a constructor. So for example:

It’s a good use-case for serializing and debugging.

Use-case 5: Make a real value from its constructor

It’s actually possible to produce a value from its constructor. We have this function

Example:

But what do you do when the constructor has fields? No sweat. We have this function:

Haskell beginners: Don’t fear the rank-N type. What it’s saying is merely that the fromConstrB function determines what the type of d will be by itself, by looking at Constr . It’s not provided externally by the caller, as it would be if the forall d. were at the same level as the a . Think of it like scope. let a = d in let d = … doesn’t make sense: the d is in a lower scope. That means we can’t just write:

The Int cannot unify with the d because the quantification is one level lower. It basically doesn’t exist outside of the (forall d. Data d => d) (nor can it escape). That’s okay, though. There is a type-class constraint which lets us be generic. We already have a function producing a value of that type:

So we can just use that:

Tada! But wait… What if there’re more fields? How do we provide more than one, and of different types?

Enter fromConstrM :

Because it’s monadic we can use a state monad to keep an index! Observe:

Let’s put this to use with fromConstrM :

In other words, keep an index starting at 0. Increase it each iteration that fromConstrM does. When we’re at index 0, return an Int , when we’re at index 1, return a Char . Easy! Right?

Use-case 6: mapping over data structures generically

A common thing to want is to map over a value in a structure-preserving way, but changing its values. For that we have gmapT :

Similar to fromConstr* , there is a rank-n type b that refers to each type in the constructor of type a . It’s easy enough to use:

Here I’m doing a little check on any field in the constructor of type Char and if it’s upper case, replacing it with ! , otherwise leaving it as-is. The first trick is to use the cast function we used earlier to reify the generic d into something real ( Char ). The second trick is to cast our concrete Char back into a generic d type.

Just like fromConstrM earlier, if you want to operate on exact indices of the constructor rather than going by type, you can use gmapM and use a state monad to do the same thing as we did before.

Use-case 7: generating from data structures generically

Another slightly different use-case is to walk over the values of a data structure, collecting the result. You can do this with gmapM and a state monad or a writer, but there’s a handy function already to do this:

Trivial example:

A more useful example can be found in structured-haskell-mode which walks over the Haskell syntax tree and collects source spans into a flat list. Another decent example is in the present package. There’s also an example in Fay to encode types to JSON with a specific Fay-runtime-specific encoding.

Printer example

Here’s a trivial (not very good, but something I wrote once) generic printer:

I wrote it because the GHC API doesn’t have Show instances for most of its data types, so it’s rather hard to actually inspect any data types that you’re working with in the REPL. It has instances for pretty printing, but pretty printing confuses presentation with data.

Example:

Note: no Show instance for Foo .

Summary

We’ve briefly covered how to query types, how to cast them, how to walk over them or generate from them. There’re other things one can do, but those are the main things. The real trick is understanding how to make the types work and that comes with a bit of experience. Fiddle around with the concepts above and you should gain an intution for what is possible with this library. See also: Data.Generics.Aliases.

Hope it helps!

© 2014-04-22 Chris Done