simulating dynamic dispatch

Simon Peyton-Jones simonpj@microsoft.com
Fri, 21 Mar 2003 08:14:10 -0000


You might also find the 'cast' function in Section 3 of "Scrap your
boilerplate" useful.
http://research.microsoft.com/~simonpj/papers/hmap/
I'm not certain, but it has the right smell.
Simon

| -----Original Message-----
| From: oleg@pobox.com [mailto:oleg@pobox.com]
| Sent: 21 March 2003 04:19
| To: hdaume@ISI.EDU; haskell@haskell.org
| Subject: Re: simulating dynamic dispatch
|=20
|=20
| > i'm hoping to be able to simulate a sort of dynamic dispatch based
on
| > class instances.
|=20
| It seems you want to dispatch based not on a type but on the
| constraint of a type.
|=20
| You code almost worked. Here's the a bit updated and working version.
|=20
| class Foo a where { foo :: a -> Bool }
| class Bar a where { bar :: a -> Bool }
|=20
| data FB =3D forall a . Foo a =3D> MkFoo a | forall a . Bar a =3D> =
MkBar a
|=20
| instance Foo FB where
|     foo (MkFoo x) =3D foo x
|=20
| instance Bar FB where
|     bar (MkBar x) =3D bar x
|=20
| -- some instances for the test
| instance Foo Int where
|     foo x =3D x =3D=3D 0
|=20
| instance Bar Char where
|     bar x =3D x =3D=3D 'a'
|=20
|=20
| test x =3D case x of
|           (MkFoo a) -> Just $ foo a
|           (MkBar a) -> Just $ bar a
| --	  _         -> Nothing
|=20
|=20
| -- *Main> test $ MkFoo (0::Int)
| -- Just True
| -- *Main> test $ MkFoo (10::Int)
| -- Just False
| -- *Main> test $ MkBar 'a'
| -- Just True
| -- *Main> test $ MkBar 'b'
| -- Just False
|=20
| _______________________________________________
| Haskell mailing list
| Haskell@haskell.org
| http://www.haskell.org/mailman/listinfo/haskell