Multiple dispatch
This allows to use the same function name applied on different arguments (types). Also known as multimethods, multiple dispatch is a mechanism to determine (at run time) which one of the functions should be called based on the type one or more of its arguments.
A first example
Assume we have a small space game with a spaceship firing missiles at asteroids. The various elements would be represented by the following data types:
data Moving-Body
x :: Int
y :: Int
vx :: Int
vy :: Int
data Ship extends Moving-Body
angle
data Asteroid extends Moving-Body
radius
data Missile extends Moving-Body
Now, if we wanted to write description functions for these, we could use:
function describe (s :: Ship) -> "This is a cool spaceship!"
function describe (a :: Asteroid) -> "This is an asteroid!"
function describe (m :: Missile) -> "...yet another missile"
objects-in-space :: [] of Moving-Body
objects-in-space = [Ship(...), Asteroid(...), Missile(...)]
do
print describe(objects-in-space.1)
print describe(objects-in-space.2)
print describe(objects-in-space.3)
The previous example would print all three different descriptions.
The same can be applied to several arguments and is the subject of the next section.
Handling collisions!
In the following example, we will handle the collison cases.
Collides with |
Ship | Asteroid |
Missile |
Ship | - |
game over |
- |
Asteroid | game over |
destroy / bounce / merge (?) |
destroy both |
Missile | - | destroy both | - |
Ambiguities
Specifyic dispatch
Note: this will be implemented at a later stage