[Haskell-cafe] Newbie question: "multi-methods" in Haskell

Tillmann Rendel rendel at rbg.informatik.tu-darmstadt.de
Mon Aug 6 14:58:56 EDT 2007


peterv schrieb:
> In de book Modern C++ design, Andrei Alexandrescu writes that Haskell
> supports “multi-methods”
> 
> http://books.google.com/books?id=aJ1av7UFBPwC&pg=PA3&ots=YPiJ_nWi6Y&dq=moder
> n+C%2B%2B&sig=FWO6SVfIrgtCWifj9yYHj3bnplQ#PPA263,M1

Chapter 11, Page 263 of this books:
> The C++ virtual function mechanism allows dispatching of a call
> depending on the dynamic type of one object. The multimethods feature
> allows dispatching of a function call depending on the types of
> multiple objects. A universally good implementation requires language
> support, wich is the route that languages such as CLOS, ML, Haskell,
> and Dylan have taken. C++ lacks such support, so it's emulation is
> left to library writers.

I do not see why the author of this book included Haskell in this list. 
(But from what I know, CLOS is more like a combinator library then like 
a language, so I don't understand the point of this list at all).

Since Haskell has no language support for subtype polymorphism or 
dynamic dispatch of method calls, there are no dynamic multimethods 
either. But with multi-parameter typeclasses, we have statically 
dispatched multimethods, of course. (See Brian's answer). But the author 
speaks specifically about dynamic dispatch.

Sometimes, class hierarchies from an OO design are naturally represented 
by algebraic data types. Then OO methods become ordinary haskell 
function, and dynamic dispatch becomes pattern matching, wich is of 
course possible on all argument positions:

   data Solid = Asteroid
              | Planet Planet

   data Planet = Earth
               | Jupiter

   collide :: Solid -> Solid -> String
   collide Asteroid (Planet Earth) = "the end of the dinos"
   collide Asteroid (Planet _) = "an asteroid hit a planet"
   collide p@(Planet _) Asteroid  = collide Asteroid p
   collide _ _ = "solids collided"

But you have to sort the definitons for collide yourself, because there 
is no "selection of the most specific" automatically. While this is a 
sometimes sensible translation of an OO design into an FP design, it is 
not the same thing as having objects and subtypes and dynamic dispatch.

   Tillmann


More information about the Haskell-Cafe mailing list