[Haskell] Dynamic binding

Bulat Ziganshin bulatz at HotPOP.com
Thu Jun 23 03:18:16 EDT 2005


Hello Andrew,

Thursday, June 23, 2005, 5:38:03 AM, you wrote:

AW> To handle the problem of drawing all shapes, in c++, I would have a list
AW> of shape pointers:

AW> struct shape{ virtual void draw(...);};
AW> struct circle : public shape {...};
AW> struct square : public shape {...};
AW> std::list<shape *> shapes;
AW> for(std::list<shape *>::iterator it = shapes.begin();it != 
AW> shapes.end();++it)
{ (*it)->>draw(...); }

AW> This general pattern of dynamic binding I use over and over again. Could 
AW> you give me some example code of this type of thing handled in Haskell's 
AW> way? Assuming that the number of classes deriving from shape might get 
AW> quite large.

just create list of draw functions itself:

[drawCircle (10,10) 5, drawSquare (20,20) 10]

you are not expected that this problem can be solved with one line of
code? :)


for more complex tasks - declare interface as a structure:

data ShapeInterface = Shape { draw :: IO (),
                              moveTo :: Point -> IO (),
                              calcArea :: Float
                            }


and return this structures from "constructor" functions:

circle x y r = Shape { draw = drawCircle center r,
                       moveTo newCenter = ....,
                       calcArea = pi*r*r
                     }
               where center = Point x y

square x y size = Shape { draw = ....,
                          moveTo newCenter = ....,
                          calcArea = size*szie
                        }

figures = [circle 1 2 3, square 4 5 6, circle 7 8 9]



of course, you cannot use inherited field names when using this
technique :)

-- 
Best regards,
 Bulat                            mailto:bulatz at HotPOP.com





More information about the Haskell mailing list