[Haskell-beginners] Typeclasses and "inheritance"

Chaddaï Fouché chaddai.fouche at gmail.com
Thu Jul 23 11:52:18 EDT 2009


On Thu, Jul 23, 2009 at 4:55 PM, Patrick
LeBoutillier<patrick.leboutillier at gmail.com> wrote:
> Hi,
>
> I'm playing around with typeclasses and trying to a feel on how you
> implement "inheritance" (not sure if that's the good word here) in Haskell.

We don't do "inheritance" in Haskell (though you can simulate it
thanks to the power of the type system you generally don't need to as
there is often a more natural solution with the other features of the
type system). It would be more usefull if you could describe what you
want to do in general and why you think you need inheritance for it.

>
> class (Show a) => IPHost a where
>
> class (Show a) => IPMask a where
>

Those class are basically synonyms of Show, is that intentional (and
really useful ?) or do you think you'll add some other functions in
there ?

> class IPAddr a where
>   host :: (IPHost b) => a -> b
>   mask :: (IPMask b) => a -> b

This definition basically say that for a given instance a of IPAddr
host can return any type that is an instance of IPHost, it so happen
that with what we saw from your code so far this means that you can't
write instances of IPAddr (since there are no function in IPHost and a
typeclass is open)... so I somehow doubt that was what you wanted to
say.
Probably you wanted something like :

> class (IPHost (Host a), IPMask (Mask a)) => IPAddr a where
>   type Host a
>   type Mask a
>   host :: a -> Host a
>   mask :: a -> Mask a

Now each instance of IPAddr will associate two type to the instancied
type, one that will be an instance of IPHost and one of IPMask.
And this function will compile :
>
> showIPAddr :: (IPAddr a) => a -> String
> showIPAddr a = (show . host $ a) ++ "/" ++ (show . mask $ a)
>


I'm equally pretty sure that's not really what you want, but without
more details I can't help much more.

-- 
Jedaï


More information about the Beginners mailing list