Schwern explained:

   >     # Following RFC 256
   >     sub name (Foo $self) : multi {
   >         return $self->{name};
   >     }
   > 
   >     sub name (Foo $self, STRING $name) : multi {
   >         $self->{name} = $name;
   >         return $self->{name};
   >     }
   > 
   > which is quite a bit simpler.

...and more efficient (since the selection is done in the core dispatcher,
not in the subroutine itself).

However, there is much more to multiple dispatch than this (technically,
Schwern's example is just subroutine overloading).

For example, here is an event handler for a GUI:

        sub handle (Window $w, Event $e) : multi {
                log("Unknown event $($e->desc) called on window $($w->name)");
        }

        sub handle (Window $w, CloseEvent $e) : multi {
                $w->close;
        }

        sub handle (ImportantWindow $w, CloseEvent $e) : multi {
                $w->close if yesno_dialog("Really close this window???");
        }

        sub handle (Window $w, MoveEvent $e) : multi {
                $w->moveto($e->newpos);
        }

        sub handle (FixedWindow $w, MoveEvent $e) : multi {
                beep();
        }

Note that the handler that is selected depends on the *combination* of
the types of the two arguments. And that the dispatcher understands
the argument/parameter inheritance relationships and selects the most
specific handler for each combination. For example, a MoveEvent sent to
a FixedWindow causes a beep, but a MoveEvent sent to any other type of
window is dispatched to the more-generic handle(Window $w, MoveEvent $e)
subroutine, which causes it to move.

Damian

Reply via email to