Subtyping

Ashley Yakeley ashley@semantic.org
Sat, 18 Aug 2001 19:08:05 -0700


At 2001-08-18 17:29, Mansour Al-Mutairi wrote:

>data SomeObject2 = SO SomeObject | SomeReal Double
...
>same2 :: SomeObject2 -> SomeObject2 -> Bool
>same2 (SomeReal a) (SomeReal b) = a == b
>same2 x y = same x y

This won't help you if you already have modules that use 'SomeObject' and 
'same'.

In OOP you can extend a 'Base' class in module M1 with a 'Derived' class 
in module M2. M1 knows nothing about 'Derived', and yet code in M1 that 
manipulates 'Base' objects will be able to handle 'Derived' objects, 
since every 'Derived' object is also a 'Base' (upcasting). Furthermore it 
is possible for M2 to determine whether a 'Base' object from a function 
or structure in M1 is also a 'Derived' object and use it appropriately 
(downcasting).

You can't do this in Haskell (or O'Haskell for that matter), though you 
could with extensible data-types:

module M1 where

     data Base = _

     foo :: Base -> Integer
     foo _ = 0

module M2 where

     data Derived = MyDerived Int Char

     data Base |= DerivedBase Derived

     foo (DerivedBase (MyDerived i _)) = i

     upcast :: Derived -> Base
     upcast = DerivedBase

     downcast :: Base -> Maybe Derived
     downcast (DerivedBase d) = Just d
     downcast _ = Nothing


-- 
Ashley Yakeley, Seattle WA