[Haskell-beginners] Typeclasses and "inheritance"

Isaac Dupree ml at isaac.cedarswampstudios.org
Fri Jul 24 15:36:19 EDT 2009


Patrick LeBoutillier wrote:
> BTW: Does what I'm trying to do make any sense at all? Does anyone know of a
> better/simpler way to do this (i.e making most of these computations
> independant of the exact underlying type)?

Actually, I would try to mostly avoid typeclasses.  If you want to 
change the representation sometime, that's still possible if you have 
abstraction!

maybe like
data IPAddr n = IPAddr n n
where typically n would be Word32 or Word128(does that exist?), and a 
polymorphic function doing math on it might use a (Num n) => context.

Actually you might sometimes need to know what kind of address it is. 
Then I guess we could have
data IPVersion = V4 | V6
class IPAddrRepr n where ipVersion :: n -> IPVersion
instance IPAddrRepr Word32 where ipVersion _ = V4
instance IPAddrRepr Word128 where ipVersion _ = V6
-- and for convenience, maybe,
instance (IPAddrRepr n) => IPAddrRepr (IPAddr n)
   where ipVersion (IPAddr n _) = ipVersion n

Alternatively I have an inkling that you could play with GADTs.  But the 
basic Haskell type system is surprisingly powerful itself!  There might 
be a way to write what you want without extensions.  It depends on 
exactly what you're trying to do.  For some purposes we might need to 
change/add to have a
data IPVersioned = V4 (IPAddr Word32) | V6 (IPAddr Word128)

-Isaac


More information about the Beginners mailing list