[Haskell] Passing typeclasses as parameters?

David Menendez dave at zednenem.com
Fri Mar 14 13:14:55 EDT 2008


On Fri, Mar 14, 2008 at 8:06 AM, Ville Tirronen <aleator at gmail.com> wrote:
> Hi all.
>
>  I managed to paint myself in a corner where I did this:
>
>  > data ShowDynamic = forall a . (Show a) => SD Dynamic a
>  > toShowDyn a = SD (toDyn a) a
>  > fromShowDyn (SD d a) = fromDynamic d
>
>  > instance Show ShowDynamic where ...
>
>  Then I began to wonder if there was any hack to do:
>
>  > data AnyDynamic X = forall a . (X a) => AD Dynamic a
>
>  which could be kinda neat, but I saw no obvious way to do this.
>  Ideas?

You can't abstract over type classes, but you can abstract over a dictionary.

    data ShowD a = ShowD { showD :: a -> String }

    data AnyDynamic dict = forall a. AD Dynamic (dict a)

On the other hand, if all you need is some fixed intersection of
classes, it's better to make your own Dynamic.

    data ShowableDynamic = forall a. (Show a, Typeable a) => SD a

    toShowDyn :: (Show a, Typeable a) => a -> ShowableDynamic
    toShowDyn = SD

    fromShowDyn :: (Show a, Typeable a) => ShowableDynamic -> Maybe a
    fromShowDyn (SD a) = cast a

Finally, you can make your own dynamic augmented with an arbitrary dictionary:

    data AnyDynamic dict = forall a. (Typeable a) => AD a (dict a)

-- 
Dave Menendez <dave at zednenem.com>
<http://www.eyrie.org/~zednenem/>


More information about the Haskell mailing list