[Template-haskell] reifyType function

Simon Peyton-Jones simonpj@microsoft.com
Mon, 7 Jul 2003 09:58:43 +0100


I think you'll find that class Typeable, defined in Data.Dynamic, is
pretty much exactly the class you describe.  It's indeed a good thing.

Simon

| -----Original Message-----
| From: template-haskell-admin@haskell.org
[mailto:template-haskell-admin@haskell.org] On Behalf Of
| Andre Pang
| Sent: 07 July 2003 09:55
| To: template-haskell@haskell.org
| Subject: [Template-haskell] reifyType function
|=20
| Hi all,
|=20
| Sean Seefried and I managed to implement a reifyType function, which
| we're calling rType since there's already that annoying built-in
| reifyType identifier ;).  It's defined in a ReifyType module which
| looks like thus:
|=20
| --8<--
| module ReifyType
| where
|=20
| import Data.Dynamic
| import Language.Haskell.THSyntax
|=20
| class ReifyType a where
|     rType :: a -> Typ
|=20
| instance (ReifyType a, ReifyType b) =3D> ReifyType (a, b) where
|     rType (_ :: (t, u)) =3D Tapp (Tapp (Tcon (Tuple 2)) (rType
(undefined
| :: t)))
|                           (rType (undefined :: u))
|=20
| instance ReifyType a =3D> ReifyType [a] where
|     rType (_ :: [t]) =3D Tapp (Tcon List) (rType (undefined :: t))
|=20
| instance Typeable a =3D> ReifyType a where
|     rType (_ :: t) =3D (Tcon (TconName typeAsString))
|        where
|           typeAsString =3D show $ typeOf (undefined :: t)
|=20
| instance (ReifyType a, ReifyType b) =3D> ReifyType (a->b) where
|    rType (_ :: t -> u)
|        =3D (Tapp (rType (undefined :: t)) (rType (undefined :: u)))
| --8<--
|=20
| An example of how to use it:
|=20
| 18:48 ~/Desktop % ghci -fglasgow-exts -fallow-overlapping-instances
| -fallow-undecidable-instances ReifyType.hs
| Type.hs)
| ...
| Loading package base ... linking ... done.
| Compiling ReifyType        ( ReifyType.hs, interpreted )
| Ok, modules loaded: ReifyType.
| *ReifyType> rType Char.toLower
| Loading package haskell98 ... linking ... done.
| Loading package haskell-src ... linking ... done.
| Tapp (Tcon (TconName "Char")) (Tcon (TconName "Char"))
| *ReifyType> rType ((+) :: (Int -> Int -> Int))
| Tapp (Tcon (TconName "Int")) (Tapp (Tcon (TconName "Int")) (Tcon
| (TconName "Int")))
| *ReifyType> rType "foobar"
| Tapp (Tcon List) (Tcon (TconName "Char"))
| *ReifyType>
|=20
| The major restriction is that you're limited to using it on
monomorphic
| types (since the typeOf function only works on monomorphic types), but
| otherwise, it seems to work remarkably well.
|=20
|=20
| --
| % Andre Pang : just.your.average.bounty.hunter
|=20
| _______________________________________________
| template-haskell mailing list
| template-haskell@haskell.org
| http://www.haskell.org/mailman/listinfo/template-haskell