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

peterv bf3 at telenet.be
Mon Aug 6 12:36:22 EDT 2007


In de book Modern C++ design, Andrei Alexandrescu writes that Haskell
supports =93multi-methods=94

http://books.google.com/books?id=3DaJ1av7UFBPwC&pg=3DPA3&ots=3DYPiJ_nWi6Y=
&dq=3Dmoder
n+C%2B%2B&sig=3DFWO6SVfIrgtCWifj9yYHj3bnplQ#PPA263,M1

How is this actually done in Haskell? Maybe this is just a basic feature =
of
Haskell which I don't grasp yet because of my object-oriented =
background?

A good example is collision between pairs of objects of type (a,b). In
object oriented languages this cannot be handled in a nice way, because
neither a.Collide(b) or b.Collide(a) is the correct approach; one would =
like
to write (a,b).Collide()

A specific example might be better here.=20

Assume the following class hierarchy:

Solid
|
+-- Asteroid
|
+-- Planet
    |
    + -- Earth
    |
    + -- Jupiter

Using multi-methods, I could write (in pseudo code)

collide (Asteroid, Planet) =3D "an asteroid hit a planet"
collide (Asteroid, Earth) =3D "the end of the dinos"
collide (Solid,Solid) =3D " solids collided"
collide (Planet, Asteroid) =3D collide (Asteroid, Planet)
collide (Earth, Asteroid)  =3D collide (Earth, Asteroid)

So basically, the "best" collide function is picked, depending on the =
type
of the arguments.

How should I write Haskell code for something like this in general, in =
the
sense that this hierarchy is typically huge and the matrix (of collide
functions for each pair of types) is very sparse.

Thanks,
Peter




No virus found in this outgoing message.
Checked by AVG Free Edition.=20
Version: 7.5.476 / Virus Database: 269.11.6/938 - Release Date: =
05/08/2007
16:16
=20



More information about the Haskell-Cafe mailing list