dynamic types

Hal Daume III hdaume@ISI.EDU
Tue, 7 Jan 2003 13:51:09 -0800 (PST)


> I'm fairly new to Haskell, but worked on Mercury until recently.
> Mercury has a type "univ" which might be declared something like:

you would write this:

data Univ = forall a . Univ a

> mkUniv :: a -> Univ

right, 'mkUniv = Univ' is sufficient.

> getValue :: Univ -> Maybe a

yes, this is the interesting bit :).  you could presumably use dynamics to
simulate this, but you'd have to do a bit of work and you wouldn't have as
general a type signature.

you could do something like

> import Data.Dynamic
> 
> data Univ = Univ Dynamic
>
> mkUniv :: Typeable a => a -> Univ
> mkUniv = Univ . toDyn
>
> getValue :: Typeable a => Univ -> Maybe a
> getValue (Univ d) = fromDynamic d

then you can do something like:

*Foo> getValue (mkUniv 'a')  :: Maybe Char
Just 'a'
*Foo> getValue (mkUniv 'a')  :: Maybe Int
Nothing

This works in GHC and Hugs (though for the version of Hugs I have you use
just Dynamic instead of Data.Dynamic).

Of course, there's no reason to have Univ in this case, you can just use
the Dynamic type.

 - Hal