simulating dynamic dispatch
oleg@pobox.com
oleg@pobox.com
Thu, 20 Mar 2003 20:19:03 -0800 (PST)
> i'm hoping to be able to simulate a sort of dynamic dispatch based on
> class instances.
It seems you want to dispatch based not on a type but on the
constraint of a type.
You code almost worked. Here's the a bit updated and working version.
class Foo a where { foo :: a -> Bool }
class Bar a where { bar :: a -> Bool }
data FB = forall a . Foo a => MkFoo a | forall a . Bar a => MkBar a
instance Foo FB where
foo (MkFoo x) = foo x
instance Bar FB where
bar (MkBar x) = bar x
-- some instances for the test
instance Foo Int where
foo x = x == 0
instance Bar Char where
bar x = x == 'a'
test x = case x of
(MkFoo a) -> Just $ foo a
(MkBar a) -> Just $ bar a
-- _ -> Nothing
-- *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