AW: Using existential types

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


At 11:25 10/10/03 +0200, Markus.Schnell at infineon.com 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'.

[1] http://haskell.org/pipermail/haskell-cafe/2003-October/005231.html

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
    etc.

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
     etc
     }

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

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

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

#g


------------
Graham Klyne
For email:
http://www.ninebynine.org/#Contact



More information about the Haskell-Cafe mailing list