AW: Using existential types

Graham Klyne GK at
Mon Oct 13 14:35:17 EDT 2003

At 11:25 10/10/03 +0200, Markus.Schnell at wrote:
>Hi Graham,
> > Instead, I replace the class instances by a single algebraic
> > data type,
> > whose members are functions corresponding to OO-style class methods.
>could you give an example?

The code in a previous message of mine [1] was an example of sorts, though 
complicated by some other issues.  Look for type 'DatatypeVal'.


A simpler example might be:

Consider a class of values called shape, for which the following operations 
are defined:

    draw :: Shape -> Canvas -> Canvas
    flip :: Shape -> Shape
    move :: Shape -> Displacement -> Shape

One can imagine defining a Haskell type class with these methods, but then 
you get the type mixing problem noted previously.  What I have found can 
work in situations like this is to define a type, thus:

data Shape = Shape
     { draw :: Canvas -> Canvas
     , flip :: Shape
     , move :: Displacement -> Shape

then one would also need methods to create different kinds of shape, e.g.:

makeSquare :: Point -> Displacement -> Shape
makeCircle :: Point -> Length -> Shape

(Assuming appropriate type definitions for Point, Displacement, Length, etc.)


Graham Klyne
For email:

More information about the Haskell-Cafe mailing list