develooper Front page | perl.perl6.language | Postings from August 2001

Re: CLOS multiple dispatch

Thread Previous | Thread Next
From:
Damian Conway
Date:
August 29, 2001 23:16
Subject:
Re: CLOS multiple dispatch
Message ID:
200108300616.RAA72163@indy05.csse.monash.edu.au
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

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About