[Haskell-cafe] Simulating OO programming with type classes;
writing a factory fu nction
Bruno Oliveira
bruno.oliveira at comlab.ox.ac.uk
Tue May 31 17:37:44 EDT 2005
Hi Alistair!
Just a "quick" reply (I didn't had time to look at Ralf's technique).
Looking at your code, it seems to me that you are missing the notion of a
supertype (perhaps, that's the intended thing with BaseClass?).
I would use an existencial type to "capture" this notion:
===========
data Base = forall c . Method c => Base c
instance BaseClass Base
instance Method Base where
method1 (Base x) i = Base (method1 x i)
method2 (Base x) = method2 x
the modifications on the code would be:
class BaseClass c => Method c where
-- method1 returns a supertype Base
method1 :: c -> Int -> Base
method2 :: c -> Int
instance Method c => Method (SubBase2 c) where
-- method1 does not fail any more
method1 x i = Base (SubBase2 (SubBase1 5))
method2 x = 2
makeSubType s =
if s == "SubBase1"
then Base (SubBase1 3)
else Base (SubBase2 (SubBase1 4))
============
Perhaps a better name for Base would be SuperMethod
(since it is really trying to capture the fact that is the super
type for Method).
Hope it helps
Cheers,
Bruno
More information about the Haskell-Cafe
mailing list