OOP

Marco Pil marcop@cs.kun.nl
Mon, 10 Nov 1997 12:45:38 +0100


Nick Kallen wrote:
> Will you be able to use type classes with dynamic types? (the answer is
> probably yes, but i'm just making sure).

 You cannot use type classes with dynamic types, yet. But we are thinking
of adding it. It might look like:

   class Drawable a
   where
      draw :: a Picture -> Picture

   instance Drawable Dynamic
   where
      draw :: Dynamic Picture -> Picture
      draw (d :: a | Drawable a) pic = draw d pic
      draw _                     pic = pic

which should be an abbreviation of the infinite function:

   instance Drawable Dynamic
   where
      draw :: Dynamic Picture -> Picture
      draw (d :: Point)   pic = draw_point d pic
      draw (d :: Circle)  pic = draw_circle d pic
      draw (d :: [Point]) pic = draw_list draw_point d pic
      :                       :
      draw _              pic = pic

For this to work, at run-time a list of instances for Drawable must be
available. Upon determining the type of the object, wrapped in the
Dynamic, the right instance can be picked (or constructed, like in
the case of a list of points).


 This also solves Nick's problem with specifying 'DrawAll', which now can
simply be written as:

   DrawAll :: [Dynamic] Picture -> Picture
   DrawAll []     pic = pic
   DrawAll [d:ds] pic = draw d (DrawAll ds pic)

the mechanism of overloading takes care that the draw function for
Dynamic objects is called.
By the way 'DrawAll' is now actually just a specific instance of:

   instance Drawable [a]   | Drawable a


 I don't think it is feasable to define a function like:

> DrawAll :: [Dynamic] Picture -> Picture | Drawable Dynamic
> DrawAll [(d :: _):ds] pic = draw d (DrawAll ds pic)
> DrawAll [] pic = pic

The compiler is not capable to determine the correct instance of
draw statically. And, if you throw away the type in the dynamic,
the computer has no way of determining the right instance dynamically
either.


Regards,

Marco