Data.Typeable and Data.Dynamic in Haskell

Tweet
Posted on February 3, 2014 by Kwang Yul Seo

This article is written in literate Haskell.

Data.Typeable is a way to implement dynamic (delayed) type checking in Haskell using a universal type.

For example, you can implement a heterogenous list in Haskell. toDyn converts any Typeable instance into Dynamic which is similar to Java Object type. Any type that is an instance of Typeable class can be wrapped with Dynamic type.

> import Data.Dynamic
> import Data.Maybe
> hlist :: [Dynamic]
> hlist = [ toDyn ("string" :: String)
>         , toDyn (7 :: Int)
>         , toDyn (pi :: Double)
>         , toDyn 'x'
>         , toDyn (((), Just "foo") :: ((), Maybe String))
>         ]
> dyn :: Dynamic
> dyn = hlist !! 1

To be precise, hlist is not actually a heterogenous list from the point of Haskell type system. It is just a homogenous list of Dynamic. The chapter 20, “Untyped Means Uni-Typed” of Harper’s textbook also emphasizes this observation: dynamic types (with typeable representations) are statically typed languages with only one type.

You can convert a Dynamic object back into an ordinary Haskell value using fromDynamic. Type checking is dynamic because it is delayed to runtime.

> v :: Int
> v = case fromDynamic dyn of
>         Nothing -> error "Type mismatch"
>         Just x  -> x

You can make any type Typeable by adding deriving Data.Typeable. In GHC, you need to turn on -XDeriveDataTypeable option to make GHC automatically derive the instance for you.

The Data.Typeable class is used primarily for generic programming in the “Scrap Your Boilerplate (SYB)” style. I will write more on this later.

References