[Haskell-cafe] Typeclasses vs simple functions?

Sean Leather leather at cs.uu.nl
Tue Sep 15 11:30:23 EDT 2009

> "Existential types" sounds a bit scary :)
It's unfortunate that they've developed a scariness feeling associated with
them. They can be used in strange ways, but simple uses are quite
approachable. One way to think of them is like implementing an
object-oriented interface. You know it's an object, but you can't do
anything with it except use the methods of the interface.


{-# LANGUAGE ExistentialQuantification #-}

data Square = Square ...
data Circle = Circle ...

class Perimeter a where perimeter :: a -> Double
instance Perimeter Square where perimeter (Square ...) = ...
instance Perimeter Circle where perimeter (Circle ...) = ...

-- The 'a' is hidden here. The interface is defined by the class constraint.
data Perimeterizable = forall a . (Perimeter a) => P a

-- This is the accessor method for things Perimeterizable.
getPerimeter (P x) = perimeter x

vals :: [Perimeterizable]
vals = [P Square, P Circle]

perims = map getPerimeter vals


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090915/74fa911f/attachment.html

More information about the Haskell-Cafe mailing list