5.11. Dynamic

The Dynamic library provides cheap-and-cheerful dynamic types for Haskell. A dynamically typed value is one which carries type information with it at run-time, and is represented here by the abstract type Dynamic. Values can be converted into Dynamic ones, which can then be combined and manipulated by the program using the operations provided over the abstract, dynamic type. One of these operations allows you to (try to) convert a dynamically-typed value back into a value with the same (monomorphic) type it had before converting it into a dynamically-typed value. If the dynamically-typed value isn't of the desired type, the coercion will fail.

The Dynamic library is capable of dealing with monomorphic types only; no support for polymorphic dynamic values, but hopefully that will be added at a later stage.

Examples where this library may come in handy (dynamic types, really - hopefully the library provided here will suffice) are: persistent programming, interpreters, distributed programming etc.

The following operations are provided over the Dynamic type:

data Dynamic -- abstract, instance of: Show, Typeable
instance Show Dynamic

toDyn       :: Typeable a => a -> Dynamic
fromDyn     :: Typeable a => Dynamic -> a -> a
fromDynamic :: Typeable a => Dynamic -> Maybe a

5.11.1. Representing types

Haskell types are represented as terms using the TypeRep abstract type:

data TypeRep  -- abstract, instance of: Eq, Show, Typeable
data TyCon    -- abstract, instance of: Eq, Show, Typeable

mkTyCon	 :: String  -> TyCon
mkAppTy	 :: TyCon   -> [TypeRep] -> TypeRep
mkFunTy  :: TypeRep -> TypeRep   -> TypeRep
applyTy	 :: TypeRep -> TypeRep   -> Maybe TypeRep

5.11.2. The Typeable class

To ease the construction of Dynamic values, we introduce the following type class to help working with TypeReps:

class Typeable a where
  typeOf :: a -> TypeRep

5.11.3. Utility functions

Operations for applying a dynamic function type to a dynamically typed argument are commonly useful, and also provided:

dynApply   :: Dynamic -> Dynamic -> Dynamic -- unsafe.
dynApplyMb :: Dynamic -> Dynamic -> Maybe Dynamic