| 1 |
<HTML> |
| 2 |
<HEAD> |
| 3 |
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> |
| 4 |
<META NAME="Generator" CONTENT="Microsoft Word 97/98"> |
| 5 |
<META NAME="GENERATOR" CONTENT="Mozilla/4.05 (Macintosh; I; PPC) [Netscape]"> |
| 6 |
<TITLE>Multiple Dispatch and Subroutine Overloading in Perl</TITLE> |
| 7 |
</HEAD> |
| 8 |
<BODY TEXT="#000000" BGCOLOR="#FFFFFF"> |
| 9 |
|
| 10 |
<CENTER> |
| 11 |
<H1> |
| 12 |
Multiple Dispatch and Subroutine Overloading in Perl</H1></CENTER> |
| 13 |
|
| 14 |
<CENTER> |
| 15 |
<H2> |
| 16 |
Damian Conway</H2></CENTER> |
| 17 |
|
| 18 |
<CENTER> |
| 19 |
<H3> |
| 20 |
School of Computer Science and Software Engineering<BR> |
| 21 |
Monash University<BR> |
| 22 |
Clayton 3168, Australia</H3></CENTER> |
| 23 |
|
| 24 |
<CENTER> |
| 25 |
<H3> |
| 26 |
<FONT FACE="Courier"><A HREF="mailto:[email protected]">[email protected]<BR> |
| 27 |
</A><A HREF="http://www.csse.monash.edu.au/~damian">http://www.csse.monash.edu.au/~damian</A></FONT></H3></CENTER> |
| 28 |
|
| 29 |
<H2> |
| 30 |
Abstract</H2> |
| 31 |
<FONT SIZE=-1><FONT FACE="Times">Sometimes Perl's standard polymorphic |
| 32 |
method dispatch mechanism isn't sophisticated enough to cope with the complexities |
| 33 |
of finding the right method to handle a given situation. For example, in |
| 34 |
a graphical user interface, objects representing events may be passed to |
| 35 |
objects representing windows. What happen next depends on the type of window, |
| 36 |
but also on the type of event. It's not enough to invoke a </FONT><FONT FACE="Courier">receive_event</FONT><FONT FACE="Times"> |
| 37 |
method on the window object, since that won't distinguish between the various |
| 38 |
possible kinds of event. Nor is it sufficient to invoke a </FONT><FONT FACE="Courier">send_to_window</FONT><FONT FACE="Times"> |
| 39 |
method on the event object, since that won't distinguish between the various |
| 40 |
possible kinds of window. What's needed is the ability to polymorphically |
| 41 |
select a suitable method for the appropriate combination of window and |
| 42 |
event types. This paper describes a new CPAN module--Class::Multimethods--that |
| 43 |
provides such a mechanism.</FONT></FONT> |
| 44 |
<H2> |
| 45 |
What is multiple dispatch?</H2> |
| 46 |
<FONT SIZE=-1><FONT FACE="Times">In object-oriented Perl, the selection |
| 47 |
of which subroutine to call in response to a method invocation (e.g. </FONT><FONT FACE="Courier">$objref->method(@args)</FONT><FONT FACE="Times">) |
| 48 |
is performed polymorphically. That means the subroutine that's invoked |
| 49 |
is the one defined in the class that the invoking object belongs to. So |
| 50 |
a call such as </FONT><FONT FACE="Courier">$objref->method(@args)</FONT><FONT FACE="Times"> |
| 51 |
invokes the method </FONT><FONT FACE="Courier">CLASSNAME::method</FONT><FONT FACE="Times">, |
| 52 |
where </FONT><FONT FACE="Courier">"CLASSNAME"</FONT><FONT FACE="Times"> |
| 53 |
is the class name returned by </FONT><FONT FACE="Courier">ref($objref)</FONT><FONT FACE="Times">.</FONT></FONT> |
| 54 |
|
| 55 |
<P><FONT SIZE=-1><FONT FACE="Times">If the class in question doesn't have |
| 56 |
a suitable method, then the dispatch procedure searches upwards through |
| 57 |
the various ancestors of the original class, looking for an appropriate |
| 58 |
subroutine. If that search fails, the dispatch procedure attempts to invoke |
| 59 |
an </FONT><FONT FACE="Courier">AUTOLOAD</FONT><FONT FACE="Times"> subroutine |
| 60 |
somewhere in the invoking object's inheritance hierarchy.</FONT></FONT> |
| 61 |
|
| 62 |
<P><FONT FACE="Times"><FONT SIZE=-1>The important point is that, whichever |
| 63 |
subroutine the method dispatcher eventually selects, it was all determined |
| 64 |
by the class of the original invoking object (i.e. according to the class |
| 65 |
of the first argument).</FONT></FONT> |
| 66 |
|
| 67 |
<P><FONT FACE="Times"><FONT SIZE=-1>For most applications, the ability |
| 68 |
to select behaviour based on the type of a single argument is sufficient. |
| 69 |
However, some applications, such as the GUI event handler mentioned above, |
| 70 |
need to select the most applicable polymorphic method on the basis of more |
| 71 |
than one argument. This behaviour is known as <I>multiple dispatch</I>.</FONT></FONT> |
| 72 |
|
| 73 |
<P><FONT FACE="Times"><FONT SIZE=-1>Generally speaking, multiple dispatch |
| 74 |
is needed whenever two or more objects belonging to different class hierarchies |
| 75 |
are going to interact, and we need to do different things depending on |
| 76 |
the combination of actual types of those objects. Typical applications |
| 77 |
that need this kind of ability include graphical user interfaces, image |
| 78 |
processing libraries, mixed-precision numerical computation systems, and |
| 79 |
most types of simulations.</FONT></FONT> |
| 80 |
|
| 81 |
<P><FONT SIZE=-1><FONT FACE="Times">It's possible to build "hand-crafted" |
| 82 |
multiply dispatched methods that look at the types of each of their arguments |
| 83 |
and react accordingly. For example, a normal (<I>singly-dispatched</I>) |
| 84 |
method could use </FONT><FONT FACE="Courier">ref</FONT><FONT FACE="Times"> |
| 85 |
or </FONT><FONT FACE="Courier">isa</FONT><FONT FACE="Times"> to determine |
| 86 |
the types of its other arguments and then select the correct behaviour |
| 87 |
in a cascaded </FONT><FONT FACE="Courier">if</FONT><FONT FACE="Times"> |
| 88 |
statement. Alternatively, it's possible to use hashes of hashes to set |
| 89 |
up a multidimensional table of subroutine references, then use the class |
| 90 |
names of the arguments (again found with </FONT><FONT FACE="Courier">ref</FONT><FONT FACE="Times">) |
| 91 |
to index into it. Both these approaches are described in detail in <A HREF="#references">[1,2]</A>.</FONT></FONT> |
| 92 |
|
| 93 |
<P><FONT FACE="Times"><FONT SIZE=-1>The problem is that such hand-crafted |
| 94 |
mechanisms are complicated to construct and even harder to debug. And because |
| 95 |
every hand-built method is structurally similar, they're also tedious to |
| 96 |
code and maintain. Life would be very much easier if it were possible to |
| 97 |
define a set of identically named methods with distinct parameter lists, |
| 98 |
and then the program would "automagically" find the right one. Such a set |
| 99 |
of multiply dispatched methods is known as a <I>multimethod</I>, and each |
| 100 |
alternative method in the set is known as a <I>variant</I>.</FONT></FONT> |
| 101 |
|
| 102 |
<P><FONT FACE="Times"><FONT SIZE=-1>But Perl has no mechanism for specifying |
| 103 |
parameter types, or for overloading subroutine names. And certainly there's |
| 104 |
no mechanism for automatically selecting between several (hypothetical) |
| 105 |
overloaded subroutines on the basis of the inheritance relationships of |
| 106 |
those (unspecifiable) parameter types.</FONT></FONT> |
| 107 |
|
| 108 |
<P><FONT FACE="Times"><FONT SIZE=-1>Until now.</FONT></FONT> |
| 109 |
<H2> |
| 110 |
The Class::Multimethods module</H2> |
| 111 |
<FONT SIZE=-1><FONT FACE="Times">The Class:Multimethod module<A HREF="#references">[3]</A> |
| 112 |
exports a subroutine (named </FONT><FONT FACE="Courier">multimethod</FONT><FONT FACE="Times">) |
| 113 |
that can be used to declare other subroutines that are to be multiply dispatched.</FONT></FONT> |
| 114 |
|
| 115 |
<P><FONT SIZE=-1><FONT FACE="Times">The new dispatch mechanism looks at |
| 116 |
the classes or types of each argument to the multimethod (by calling </FONT><FONT FACE="Courier">ref</FONT><FONT FACE="Times"> |
| 117 |
on each) and determines the "closest" matching variant of the multimethod, |
| 118 |
according to the parameter types specified in the variants' definitions |
| 119 |
(see below for a definition of "closest").</FONT></FONT> |
| 120 |
|
| 121 |
<P><FONT FACE="Times"><FONT SIZE=-1>The result is something akin to C++'s |
| 122 |
function overloading but more sophisticated, since multimethods take the |
| 123 |
inheritance relationships of each argument into account. Another way of |
| 124 |
thinking of the mechanism is that it performs polymorphic dispatch on every |
| 125 |
argument of a method, not just on the first.</FONT></FONT> |
| 126 |
<H2> |
| 127 |
Defining multimethods</H2> |
| 128 |
<FONT SIZE=-1><FONT FACE="Courier">Class::Multimethods::multimethod</FONT><FONT FACE="Times"> |
| 129 |
can be used to specify multimethod variants with the dispatch behaviour |
| 130 |
described above. It takes the name of the desired multimethod, a list of |
| 131 |
class names, and a subroutine reference, and uses this information to generate |
| 132 |
a corresponding multimethod variant within the current package.</FONT></FONT> |
| 133 |
|
| 134 |
<P><FONT FACE="Times"><FONT SIZE=-1>For example:</FONT></FONT> |
| 135 |
<PRE>package LargeInt; @ISA = (LargeNum); |
| 136 |
package LargeFloat; @ISA = (LargeNum); |
| 137 |
|
| 138 |
package LargeNum; |
| 139 |
use Class::Multimethods; |
| 140 |
|
| 141 |
multimethod |
| 142 |
divide => (LargeInt, LargeInt) => |
| 143 |
sub { |
| 144 |
LargeInt::divide($_[0],$_[1]) |
| 145 |
}; |
| 146 |
|
| 147 |
multimethod |
| 148 |
divide => (LargeInt, LargeFloat), |
| 149 |
sub { |
| 150 |
LargeFloat::divide($_[0]->AsLargeFloat(), $_[1]); |
| 151 |
};</PRE> |
| 152 |
<FONT SIZE=-1><FONT FACE="Times">This creates a (single) multimethod called |
| 153 |
</FONT><FONT FACE="Courier">LargeNum::divide</FONT><FONT FACE="Times"> |
| 154 |
with two variants. If the multimethod is called with two references to |
| 155 |
</FONT><FONT FACE="Courier">LargeInt</FONT><FONT FACE="Times"> objects |
| 156 |
as arguments, the first variant is invoked. If the multimethod is called |
| 157 |
with a </FONT><FONT FACE="Courier">LargeInt</FONT><FONT FACE="Times"> reference |
| 158 |
and a </FONT><FONT FACE="Courier">LargeFloat</FONT><FONT FACE="Times"> |
| 159 |
reference, the second variant is called.</FONT></FONT> |
| 160 |
|
| 161 |
<P><FONT SIZE=-1><FONT FACE="Times">Calling the multimethod with any other |
| 162 |
combination of </FONT><FONT FACE="Courier">LargeNum</FONT><FONT FACE="Times"> |
| 163 |
reference arguments (e.g. a reference to a </FONT><FONT FACE="Courier">LargeFloat</FONT><FONT FACE="Times"> |
| 164 |
and a reference to a </FONT><FONT FACE="Courier">LargeInt</FONT><FONT FACE="Times">, |
| 165 |
or two </FONT><FONT FACE="Courier">LargeFloat</FONT><FONT FACE="Times"> |
| 166 |
references) results in an exception being thrown, with the message:</FONT></FONT> |
| 167 |
<PRE><FONT FACE="Helvetica">No viable candidate for call to multimethod LargeNum::divide</FONT></PRE> |
| 168 |
<FONT FACE="Times"><FONT SIZE=-1>To avoid this, a "catch-all" variant could |
| 169 |
be specified:</FONT></FONT> |
| 170 |
<PRE>multimethod |
| 171 |
divide => (LargeNum, LargeNum) => |
| 172 |
sub { |
| 173 |
LargeFloat::divide($_[0]->AsLargeFloat(), $_[1]->AsLargeFloat()); |
| 174 |
};</PRE> |
| 175 |
<FONT SIZE=-1><FONT FACE="Times">Now, calling </FONT><FONT FACE="Courier">LargeNum::divide</FONT><FONT FACE="Times"> |
| 176 |
with (for example) a </FONT><FONT FACE="Courier">LargeFloat</FONT><FONT FACE="Times"> |
| 177 |
reference and a </FONT><FONT FACE="Courier">LargeInt</FONT><FONT FACE="Times"> |
| 178 |
reference causes this third variant to be invoked. That's because a </FONT><FONT FACE="Courier">LargeFloat</FONT><FONT FACE="Times"> |
| 179 |
<I>is-a</I> </FONT><FONT FACE="Courier">LargeNum</FONT><FONT FACE="Times"> |
| 180 |
(so the first argument is compatible with the first parameter), and a </FONT><FONT FACE="Courier">LargeInt</FONT><FONT FACE="Times"> |
| 181 |
<I>is-a</I> </FONT><FONT FACE="Courier">LargeNum</FONT><FONT FACE="Times"> |
| 182 |
too (so the second argument is compatible with the second parameter). Note |
| 183 |
that adding this third variant doesn't affect calls to the other two, since |
| 184 |
Class::Multimethods always selects the nearest match (see the next section |
| 185 |
for details of what <I>nearest</I> means).</FONT></FONT> |
| 186 |
|
| 187 |
<P><FONT SIZE=-1><FONT FACE="Times">This general "best fit" behaviour is |
| 188 |
extremely useful, because it means you can code the specific cases you |
| 189 |
want to handle (e.g. </FONT><FONT FACE="Courier">(LargeInt, LargeFloat)</FONT><FONT FACE="Times">), |
| 190 |
and then provide one or more "catch-all" cases (e.g. </FONT><FONT FACE="Courier">(LargeNum, |
| 191 |
LargeNum)</FONT><FONT FACE="Times">) to deal with any other combination |
| 192 |
of arguments. The multimethod automatically picks the most suitable variant |
| 193 |
to handle each actual argument list.</FONT></FONT> |
| 194 |
<H2> |
| 195 |
Finding the "nearest" multimethod</H2> |
| 196 |
<FONT FACE="Times"><FONT SIZE=-1>Of course, the usefulness of the entire |
| 197 |
system depends on how intelligently Class::Multimethods decides which version |
| 198 |
of a multimethod is "nearest" to a given set of arguments. That decision |
| 199 |
process is called <I>dispatch resolution</I>, and Class::Multimethods does |
| 200 |
it like this:</FONT></FONT> |
| 201 |
<OL> |
| 202 |
<LI> |
| 203 |
<FONT SIZE=-1><FONT FACE="Times">If the types of the arguments given (as |
| 204 |
determined by applying </FONT><FONT FACE="Courier">ref</FONT><FONT FACE="Times"> |
| 205 |
to each in turn) exactly match the set of parameter types specified in |
| 206 |
any variant of the multimethod, that variant is immediately called.</FONT></FONT></LI> |
| 207 |
|
| 208 |
<LI> |
| 209 |
<FONT FACE="Times"><FONT SIZE=-1>Otherwise, Class::Multimethods compiles |
| 210 |
a list of <I>viable targets</I>. A viable target is a variant of the multimethod |
| 211 |
with the same number of parameters as there were arguments passed. In addition, |
| 212 |
for each parameter the specified parameter type must be a base class of |
| 213 |
the actual type of the corresponding argument in the actual call (i.e. |
| 214 |
each argument must belong to a subclass of the corresponding parameter |
| 215 |
type).</FONT></FONT></LI> |
| 216 |
|
| 217 |
<LI> |
| 218 |
<FONT FACE="Times"><FONT SIZE=-1>If there is only one viable target, it |
| 219 |
is called immediately. If there are no viable targets, an exception is |
| 220 |
thrown indicating that the multimethod can't handle the specific set of |
| 221 |
arguments.</FONT></FONT></LI> |
| 222 |
|
| 223 |
<LI> |
| 224 |
<FONT FACE="Times"><FONT SIZE=-1>Otherwise, Class::Multimethod examines |
| 225 |
each viable target and computes its <I>inheritance distance</I> from the |
| 226 |
actual set of arguments. The inheritance distance from a single argument |
| 227 |
to the corresponding parameter is the number of inheritance steps between |
| 228 |
their respective classes (working up the tree from argument to parameter). |
| 229 |
If there's no inheritance path between them, the distance is infinite. |
| 230 |
The inheritance distance for a set of arguments is just the sum of their |
| 231 |
individual inheritance distances.</FONT></FONT></LI> |
| 232 |
|
| 233 |
<LI> |
| 234 |
<FONT FACE="Times"><FONT SIZE=-1>Class::Multimethod then chooses the viable |
| 235 |
target with the smallest inheritance distance as the actual target. If |
| 236 |
more than one viable target has the same smallest distance, the call is |
| 237 |
ambiguous. In that case, the dispatch process fails and an exception is |
| 238 |
thrown. If there's only a single actual target, Class::Multimethod records |
| 239 |
its identity in a special cache, so the distance computations don't have |
| 240 |
to be repeated next time the same set of argument types is used . The actual |
| 241 |
target is then called and the dispatch process is complete.</FONT></FONT></LI> |
| 242 |
</OL> |
| 243 |
|
| 244 |
<H2> |
| 245 |
Declaring multimethods</H2> |
| 246 |
<FONT FACE="Times"><FONT SIZE=-1>Class::Multimethods doesn't care which |
| 247 |
packages the individual variants of a multimethod are defined in. Every |
| 248 |
variant of a multimethod is visible to the underlying multimethod dispatcher, |
| 249 |
no matter where it was defined. In other words, all multimethod variants |
| 250 |
share a common namespace that is independent of their individual package |
| 251 |
namespaces.</FONT></FONT> |
| 252 |
|
| 253 |
<P><FONT SIZE=-1><FONT FACE="Times">For example, the three variants for |
| 254 |
the </FONT><FONT FACE="Courier">divide</FONT><FONT FACE="Times"> multimethod |
| 255 |
shown above could all be defined in the </FONT><FONT FACE="Courier">LargeNum</FONT><FONT FACE="Times"> |
| 256 |
package, or the </FONT><FONT FACE="Courier">LargeFloat</FONT><FONT FACE="Times"> |
| 257 |
package or the </FONT><FONT FACE="Courier">LargeInt</FONT><FONT FACE="Times"> |
| 258 |
package, or in the main package, or anywhere else. They don't even have |
| 259 |
to be declared in the same package.</FONT></FONT> |
| 260 |
|
| 261 |
<P><FONT FACE="Times"><FONT SIZE=-1>Of course, to enable a specific multimethod |
| 262 |
to be <I>called</I> within a given package, the package must know about |
| 263 |
it. That can be achieved by specifying just the name of the multimethod |
| 264 |
(i.e. with no argument list or variant code), much like a standard Perl |
| 265 |
subroutine declaration:</FONT></FONT> |
| 266 |
<PRE>package Some::Other::Package; |
| 267 |
use Class::Multimethods; |
| 268 |
|
| 269 |
<I><FONT FACE="Courier"># import "divide" multimethod |
| 270 |
</FONT></I>multimethod "divide";</PRE> |
| 271 |
<FONT FACE="Times"><FONT SIZE=-1>For convenience, the two steps can be |
| 272 |
consolidated, and the declaration abbreviated to:</FONT></FONT> |
| 273 |
<PRE>package Some::Other::Package; |
| 274 |
use Class::Multimethods "divide";</PRE> |
| 275 |
|
| 276 |
<H2> |
| 277 |
Subroutine overloading</H2> |
| 278 |
<FONT FACE="Times"><FONT SIZE=-1>Class::Multimethod also doesn't care whether |
| 279 |
multimethods are called as methods or as regular subroutines. This is quite |
| 280 |
different from the behaviour of normal Perl methods and subroutines, where |
| 281 |
how you call them determines how they're dispatched.</FONT></FONT> |
| 282 |
|
| 283 |
<P><FONT FACE="Times"><FONT SIZE=-1>With multimethods, since all arguments |
| 284 |
participate in the polymorphic resolution of a call (instead of just the |
| 285 |
first), it make no difference whether a multimethod is called as a method:</FONT></FONT> |
| 286 |
<PRE>$num3 = $num1->divide($num2);</PRE> |
| 287 |
<FONT FACE="Times"><FONT SIZE=-1>or a subroutine:</FONT></FONT> |
| 288 |
<PRE>$num3 = divide($num1, $num2);</PRE> |
| 289 |
<FONT FACE="Times"><FONT SIZE=-1>That means that Class::Multimethods also |
| 290 |
provides general subroutine overloading. For example:</FONT></FONT> |
| 291 |
<PRE>package main; |
| 292 |
use IO; |
| 293 |
use Class::Multimethods; |
| 294 |
|
| 295 |
multimethod |
| 296 |
test => (IO::File, DataSource) => |
| 297 |
sub { |
| 298 |
$_[0]->print( $_[1]->data() ) |
| 299 |
}; |
| 300 |
|
| 301 |
multimethod |
| 302 |
test => (IO::Pipe, Queue) => |
| 303 |
sub { |
| 304 |
$_[0]->print( $_[1]->next() ) |
| 305 |
while $_[1]->count(); |
| 306 |
}; |
| 307 |
|
| 308 |
multimethod |
| 309 |
test => (IO::Socket, Stack) => |
| 310 |
sub { |
| 311 |
$_[0]->print( $_[1]->pop() ) |
| 312 |
}; |
| 313 |
|
| 314 |
<I><FONT FACE="Courier"># and later... |
| 315 |
|
| 316 |
</FONT></I>test($some_handle, $some_data_ref);</PRE> |
| 317 |
|
| 318 |
<H2> |
| 319 |
Non-class types as parameters</H2> |
| 320 |
<FONT SIZE=-1><FONT FACE="Times">Yet another thing Class::Multimethods |
| 321 |
doesn't care about is whether the parameter types for each multimethod |
| 322 |
variant are the names of "real" classes, or just the identifiers returned |
| 323 |
when raw Perl data types are passed to the built-in </FONT><FONT FACE="Courier">ref</FONT><FONT FACE="Times"> |
| 324 |
function. That means multimethod variants can also be defined like this:</FONT></FONT> |
| 325 |
<PRE>multimethod stringify => (ARRAY) => |
| 326 |
sub { |
| 327 |
my @arg = @{$_[0]}; |
| 328 |
return "[" . join(", ",@arg) . "]"; |
| 329 |
}; |
| 330 |
|
| 331 |
multimethod stringify => (HASH) => |
| 332 |
sub { |
| 333 |
my %arg = %{$_[0]}; |
| 334 |
return "{" . join(", ", map( "$_=>$arg{$_}", keys %arg) ) . "}"; |
| 335 |
}; |
| 336 |
|
| 337 |
multimethod stringify => (CODE) => |
| 338 |
sub { return "sub {???}" }; |
| 339 |
|
| 340 |
<I><FONT FACE="Courier"># and later... |
| 341 |
|
| 342 |
</FONT></I>print stringify([1,2,3]); |
| 343 |
print stringify({a=>1,b=>2,c=>3}); |
| 344 |
print stringify($array_or_hash_ref);</PRE> |
| 345 |
<FONT SIZE=-1><FONT FACE="Times">In other words, the names of built-in |
| 346 |
types (i.e. those returned by </FONT><FONT FACE="Courier">ref</FONT><FONT FACE="Times">) |
| 347 |
are perfectly acceptable as multimethod parameters. That's a nice bonus, |
| 348 |
but there's a problem. Because </FONT><FONT FACE="Courier">ref</FONT><FONT FACE="Times"> |
| 349 |
returns </FONT><FONT FACE="Courier">undef</FONT><FONT FACE="Times"> when |
| 350 |
given any literal string or numeric value, the following code:</FONT></FONT> |
| 351 |
<PRE>$str = "a multiple dispatch oddity"; |
| 352 |
print stringify( 2001 ); |
| 353 |
print stringify( $str );</PRE> |
| 354 |
<FONT FACE="Times"><FONT SIZE=-1>will produce a nasty surprise:</FONT></FONT> |
| 355 |
<PRE><FONT FACE="Helvetica">No viable candidate for call to multimethod stringify() at line 1</FONT></PRE> |
| 356 |
<FONT SIZE=-1><FONT FACE="Times">That's because the dispatch resolution |
| 357 |
process first calls </FONT><FONT FACE="Courier">ref(2001)</FONT><FONT FACE="Times"> |
| 358 |
to get the class name for the first argument, and therefore thinks it's |
| 359 |
of class </FONT><FONT FACE="Courier">undef</FONT><FONT FACE="Times">. Since |
| 360 |
there's no </FONT><FONT FACE="Courier">stringify</FONT><FONT FACE="Times"> |
| 361 |
variant with </FONT><FONT FACE="Courier">undef</FONT><FONT FACE="Times"> |
| 362 |
as its parameter type, there are no viable targets for the multimethod |
| 363 |
call. Hence the exception.</FONT></FONT> |
| 364 |
|
| 365 |
<P><FONT SIZE=-1><FONT FACE="Times">To overcome this limitation, Class::Multimethods |
| 366 |
allows three special pseudo-type names within the parameter lists of multimethod |
| 367 |
variants. The first pseudo-type--</FONT><FONT FACE="Courier">'$'--</FONT><FONT FACE="Times">is |
| 368 |
the class Class::Multimethods pretends any scalar value (except a reference) |
| 369 |
belongs to. Hence, the following definition makes the two recalcitrant |
| 370 |
stringifications of scalars work correctly:</FONT></FONT> |
| 371 |
<PRE>multimethod stringify => ('$') => |
| 372 |
sub { return qq("$_[0]") };</PRE> |
| 373 |
<FONT FACE="Times"><FONT SIZE=-1>With that definition in place, the two |
| 374 |
calls:</FONT></FONT> |
| 375 |
<PRE>print stringify( 2001 ); |
| 376 |
print stringify( $str );</PRE> |
| 377 |
<FONT FACE="Times"><FONT SIZE=-1>would produce:</FONT></FONT> |
| 378 |
<PRE><FONT FACE="Helvetica">"2001" |
| 379 |
"a multiple dispatch oddity"</FONT></PRE> |
| 380 |
<FONT SIZE=-1><FONT FACE="Times">That solves the problem, but not as elegantly |
| 381 |
as it might. It would be better if numeric values were left unquoted. To |
| 382 |
this end, Class::Multimethods offers a second pseudo-type--</FONT><FONT FACE="Courier">"#"--</FONT><FONT FACE="Times">which |
| 383 |
is the class it pretends numeric scalar values belong to. Hence, the following |
| 384 |
additional variant removes the quotes from stringified numbers:</FONT></FONT> |
| 385 |
<PRE>multimethod stringify => ('#') => |
| 386 |
sub { return $_[0] };</PRE> |
| 387 |
<FONT SIZE=-1><FONT FACE="Times">The final pseudo-type--</FONT><FONT FACE="Courier">"*"</FONT><FONT FACE="Times">--is |
| 388 |
a wild-card or "don't care" type specifier, which matches any argument |
| 389 |
type exactly. For example, we could provide a "catch-all" stringify variant |
| 390 |
(to handle </FONT><FONT FACE="Courier">"GLOB"</FONT><FONT FACE="Times"> |
| 391 |
or </FONT><FONT FACE="Courier">"IO"</FONT><FONT FACE="Times"> references, |
| 392 |
for example):</FONT></FONT> |
| 393 |
<PRE>multimethod stringify => ('*') => |
| 394 |
sub { |
| 395 |
croak "can't stringify a " . ref($_[0]); |
| 396 |
}</PRE> |
| 397 |
<FONT SIZE=-1><FONT FACE="Times">Note that, even though the </FONT><FONT FACE="Courier">"*"</FONT><FONT FACE="Times"> |
| 398 |
variant matches any possible argument type, it does so with a greater inheritance |
| 399 |
distance than any other possible match. In other words, a </FONT><FONT FACE="Courier">"*"</FONT><FONT FACE="Times"> |
| 400 |
variant is a last resort, used only if every other variant is unviable.</FONT></FONT> |
| 401 |
<H2> |
| 402 |
Recursive multiple dispatch</H2> |
| 403 |
<FONT SIZE=-1><FONT FACE="Times">As defined above, the </FONT><FONT FACE="Courier">stringify</FONT><FONT FACE="Times"> |
| 404 |
multimethod still fails rather badly on nested data structures. For example:</FONT></FONT> |
| 405 |
<PRE>print stringify( |
| 406 |
{ a => [1,2,3], |
| 407 |
b => {b1=>4,b2=>5}, |
| 408 |
c => sub{3} |
| 409 |
} |
| 410 |
);</PRE> |
| 411 |
<FONT FACE="Times"><FONT SIZE=-1>will print out something like:</FONT></FONT> |
| 412 |
<PRE>{<FONT FACE="Helvetica">a=>ARRAY(0x1001c23e), b=>HASH(0x10023ae6), c=>CODE(0x10027698)}</FONT></PRE> |
| 413 |
<FONT SIZE=-1><FONT FACE="Times">because when the hash reference is passed |
| 414 |
to the </FONT><FONT FACE="Courier">HASH</FONT><FONT FACE="Times"> variant |
| 415 |
of </FONT><FONT FACE="Courier">stringify</FONT><FONT FACE="Times">, each |
| 416 |
of its keys and values is interpolated directly into the returned string, |
| 417 |
rather than being individually stringified.</FONT></FONT> |
| 418 |
|
| 419 |
<P><FONT SIZE=-1><FONT FACE="Times">Fortunately a small tweak to the </FONT><FONT FACE="Courier">ARRAY</FONT><FONT FACE="Times"> |
| 420 |
and </FONT><FONT FACE="Courier">HASH</FONT><FONT FACE="Times"> variants |
| 421 |
solves the problem:</FONT></FONT> |
| 422 |
<PRE>multimethod stringify => (ARRAY) => |
| 423 |
sub { |
| 424 |
<FONT FACE="Courier"> <B>my @arg = map { stringify($_) } @{$_[0]}; </B></FONT> |
| 425 |
return "[" . join(", ",@arg) . "]"; |
| 426 |
}; |
| 427 |
|
| 428 |
multimethod stringify => (HASH) => |
| 429 |
sub { |
| 430 |
<B><FONT FACE="Courier">my %arg = map { stringify($_) } %{$_[0]}; |
| 431 |
</FONT></B> return "{" . join(", ", map("$_=>$arg{$_}", keys %arg)) . "}"; |
| 432 |
};</PRE> |
| 433 |
<FONT SIZE=-1><FONT FACE="Times">The difference here is that each element |
| 434 |
in the array or hash is recursively stringified (within the </FONT><FONT FACE="Courier">map</FONT><FONT FACE="Times"> |
| 435 |
operation) before the container itself is processed. And because </FONT><FONT FACE="Courier">stringify</FONT><FONT FACE="Times"> |
| 436 |
is a multimethod, there's no need for any special logic inside the </FONT><FONT FACE="Courier">map</FONT><FONT FACE="Times"> |
| 437 |
block to distinguish the various possible nested data types. Instead, the |
| 438 |
recursive calls automatically select the appropriate variant for each element, |
| 439 |
so nested references and values are correctly processed. So now the call:</FONT></FONT> |
| 440 |
<PRE>print stringify( |
| 441 |
{ a => [1,2,3], |
| 442 |
b => {b1=>4,b2=>5}, |
| 443 |
c => sub{3} |
| 444 |
} |
| 445 |
);</PRE> |
| 446 |
<FONT FACE="Times"><FONT SIZE=-1>prints:</FONT></FONT> |
| 447 |
<PRE>{<FONT FACE="Helvetica">"a"=>[1, 2, 3], "b"=>{"b1"=>4, "b2"=>5}, "c"=>sub{???}}</FONT></PRE> |
| 448 |
|
| 449 |
<H2> |
| 450 |
Resolving ambiguities and non-dispatchable calls</H2> |
| 451 |
<FONT SIZE=-1><FONT FACE="Times">It's relatively easy to set up a multimethod |
| 452 |
such that particular combinations of argument types cannot be correctly |
| 453 |
dispatched. For example, consider the following variants of a multimethod |
| 454 |
called </FONT><FONT FACE="Courier">put_peg</FONT><FONT FACE="Times">:</FONT></FONT> |
| 455 |
<PRE>class RoundPeg; @ISA = ( 'Peg' ); |
| 456 |
class SquareHole; @ISA = ( 'Hole' ); |
| 457 |
|
| 458 |
multimethod |
| 459 |
put_peg => (RoundPeg,Hole) => |
| 460 |
sub { |
| 461 |
print "round peg in hole\n" |
| 462 |
}; |
| 463 |
|
| 464 |
multimethod |
| 465 |
put_peg => (Peg,SquareHole) => |
| 466 |
sub { |
| 467 |
print "peg in square hole\n" |
| 468 |
}; |
| 469 |
|
| 470 |
multimethod |
| 471 |
put_peg => (Peg,Hole) => |
| 472 |
sub { |
| 473 |
print "a peg in a hole\n" |
| 474 |
};</PRE> |
| 475 |
<FONT SIZE=-1><FONT FACE="Times">If </FONT><FONT FACE="Courier">put_peg</FONT><FONT FACE="Times"> |
| 476 |
is called like this:</FONT></FONT> |
| 477 |
<PRE>my $peg = RoundPeg->new(); |
| 478 |
my $hole = SquareHole->new(); |
| 479 |
|
| 480 |
put_peg($peg, $hole);</PRE> |
| 481 |
<FONT SIZE=-1><FONT FACE="Times">then Class::Multimethods can't dispatch |
| 482 |
the call, because it cannot decide between the variants</FONT><FONT FACE="Courier"> |
| 483 |
(RoundPeg,Hole)</FONT><FONT FACE="Times"> and </FONT><FONT FACE="Courier">(Peg,SquareHole)</FONT><FONT FACE="Times">, |
| 484 |
each of which is the same inheritance distance (i.e. 1 derivation) from |
| 485 |
the actual arguments.</FONT></FONT> |
| 486 |
|
| 487 |
<P><FONT FACE="Times"><FONT SIZE=-1>The default behaviour is to throw an |
| 488 |
exception like this:</FONT></FONT> |
| 489 |
<PRE><FONT FACE="Helvetica">Cannot resolve call to multimethod put_peg(RoundPeg,SquareHole). |
| 490 |
The multimethods: |
| 491 |
put_peg(RoundPeg,Hole) |
| 492 |
put_peg(Peg,SquareHole) |
| 493 |
are equally viable</FONT></PRE> |
| 494 |
<FONT SIZE=-1><FONT FACE="Times">Sometimes, however, the more specialized |
| 495 |
variants are only optimizations, and a more general variant (in this case, |
| 496 |
the </FONT><FONT FACE="Courier">(Peg,Hole)</FONT><FONT FACE="Times"> variant) |
| 497 |
would suffice as a default where such an ambiguity exists. In such situations, |
| 498 |
it's possible to tell Class::Multimethods to resolve the ambiguity by calling |
| 499 |
that general variant.</FONT></FONT> |
| 500 |
|
| 501 |
<P><FONT SIZE=-1><FONT FACE="Times">The </FONT><FONT FACE="Courier">resolve_ambiguous</FONT><FONT FACE="Times"> |
| 502 |
subroutine is automatically exported by Class::Multimethods and is used |
| 503 |
like this:</FONT></FONT> |
| 504 |
<PRE>resolve_ambiguous |
| 505 |
put_peg => (Peg,Hole);</PRE> |
| 506 |
<FONT FACE="Times"><FONT SIZE=-1>That is, it takes the name of the multimethod |
| 507 |
being "disambiguated", and the parameter list of the variant that is to |
| 508 |
be the default for ambiguous cases. Of course, the specified variant must |
| 509 |
actually exist at the time of the call. If it doesn't, Class::Multimethod |
| 510 |
ignores it and throws the usual exception.</FONT></FONT> |
| 511 |
|
| 512 |
<P><FONT FACE="Times"><FONT SIZE=-1>Alternatively, if no variant is suitable |
| 513 |
as a default, some other (non-multimethod) subroutine can be registered |
| 514 |
instead:</FONT></FONT> |
| 515 |
<PRE>resolve_ambiguous |
| 516 |
put_peg => \&disambiguator;</PRE> |
| 517 |
<FONT SIZE=-1><FONT FACE="Times">Now, whenever </FONT><FONT FACE="Courier">put_peg</FONT><FONT FACE="Times"> |
| 518 |
can't dispatch a call because it's ambiguous, </FONT><FONT FACE="Courier">disambiguator</FONT><FONT FACE="Times"> |
| 519 |
will be called instead, with the same argument list as </FONT><FONT FACE="Courier">put_peg</FONT><FONT FACE="Times"> |
| 520 |
was given.</FONT></FONT> |
| 521 |
|
| 522 |
<P><FONT SIZE=-1><FONT FACE="Times">Of course, </FONT><FONT FACE="Courier">resolve_ambiguous</FONT><FONT FACE="Times"> |
| 523 |
doesn't care what kind of subroutine it's given a reference to, so you |
| 524 |
can also use an anonymous subroutine:</FONT></FONT> |
| 525 |
<PRE>resolve_ambiguous |
| 526 |
put_peg => sub { |
| 527 |
print "can't put a ", ref($_[0]), " into a ", ref($_[1]), "\n"; |
| 528 |
};</PRE> |
| 529 |
<FONT FACE="Times"><FONT SIZE=-1>Dispatch can also fail if there are no |
| 530 |
suitable variants available to handle a particular call. For example:</FONT></FONT> |
| 531 |
<PRE>my $peg = JPEG->new(); |
| 532 |
my $hole = Loophole->new(); |
| 533 |
|
| 534 |
put_peg($peg, $hole);</PRE> |
| 535 |
<FONT FACE="Times"><FONT SIZE=-1>which would normally produce the exception:</FONT></FONT> |
| 536 |
<PRE><FONT FACE="Helvetica">No viable candidate for call to multimethod put_peg(JPEG,Loophole)</FONT></PRE> |
| 537 |
<FONT SIZE=-1><FONT FACE="Times">since classes </FONT><FONT FACE="Courier">JPEG</FONT><FONT FACE="Times"> |
| 538 |
and </FONT><FONT FACE="Courier">Loophole</FONT><FONT FACE="Times"> aren't |
| 539 |
in the </FONT><FONT FACE="Courier">Peg</FONT><FONT FACE="Times"> and </FONT><FONT FACE="Courier">Hole</FONT><FONT FACE="Times"> |
| 540 |
hierarchies, so there's no inheritance path back to a more general variant.</FONT></FONT> |
| 541 |
|
| 542 |
<P><FONT SIZE=-1><FONT FACE="Times">The </FONT><FONT FACE="Courier">resolve_no_match</FONT><FONT FACE="Times"> |
| 543 |
subroutine, which is also exported from Class::Multimethods, can be used |
| 544 |
to set up a handler for such cases. For example:</FONT></FONT> |
| 545 |
<PRE>resolve_no_match |
| 546 |
put_peg => sub { |
| 547 |
my ($p, $h) = map {ref} @_; |
| 548 |
|
| 549 |
$_[0]->display($_[1]) |
| 550 |
if $p =~ /[JM]PEG/; |
| 551 |
|
| 552 |
call_plumber() |
| 553 |
if $p eq 'ClothesPeg' && $h eq 'DrainHole'; |
| 554 |
|
| 555 |
<I> <FONT FACE="Courier"># etc. |
| 556 |
</FONT></I> };</PRE> |
| 557 |
<FONT SIZE=-1><FONT FACE="Times">As with </FONT><FONT FACE="Courier">resolve_ambiguous</FONT><FONT FACE="Times">, |
| 558 |
the variant or subroutine registered with </FONT><FONT FACE="Courier">resolve_no_match</FONT><FONT FACE="Times"> |
| 559 |
is called with the same set of arguments that were passed to the original |
| 560 |
multimethod call.</FONT></FONT> |
| 561 |
<H2> |
| 562 |
Debugging a multimethod</H2> |
| 563 |
<FONT SIZE=-1><FONT FACE="Times">Class::Multimethods provides a (non-exported) |
| 564 |
subroutine called </FONT><FONT FACE="Courier">analyse</FONT><FONT FACE="Times">, |
| 565 |
which takes the name of a multimethod and generates a report (to </FONT><FONT FACE="Courier">STDERR</FONT><FONT FACE="Times">) |
| 566 |
listing the behaviour of that multimethod under all feasible combinations |
| 567 |
of its various potential arguments. For example, given the definitions |
| 568 |
of the </FONT><FONT FACE="Courier">test</FONT><FONT FACE="Times"> multimethod |
| 569 |
shown earlier, a call to:</FONT></FONT> |
| 570 |
<PRE>Class::Multimethods::analyse("test");</PRE> |
| 571 |
<FONT SIZE=-1><FONT FACE="Times">will print out an analysis of the dispatch |
| 572 |
behaviour for all possible combinations of an </FONT><FONT FACE="Courier">IO::File</FONT><FONT FACE="Times">, |
| 573 |
</FONT><FONT FACE="Courier">IO::Pipe</FONT><FONT FACE="Times">, or </FONT><FONT FACE="Courier">IO::Socket</FONT><FONT FACE="Times"> |
| 574 |
object (as the first argument), and a </FONT><FONT FACE="Courier">DataSource</FONT><FONT FACE="Times">, |
| 575 |
</FONT><FONT FACE="Courier">Queue</FONT><FONT FACE="Times">, or </FONT><FONT FACE="Courier">Stack</FONT><FONT FACE="Times"> |
| 576 |
object (as the second argument). Furthermore </FONT><FONT FACE="Courier">analyse</FONT><FONT FACE="Times"> |
| 577 |
will examine the class hierarchies of which these classes are a part, and |
| 578 |
generate test cases for any ancestral or descendant classes as well. For |
| 579 |
instance, for the first argument it will also test objects of the classes |
| 580 |
</FONT><FONT FACE="Courier">IO::Handle</FONT><FONT FACE="Times">, and </FONT><FONT FACE="Courier">IO::Seekable</FONT><FONT FACE="Times">, |
| 581 |
(since these are both ancestral classes of </FONT><FONT FACE="Courier">IO::File</FONT><FONT FACE="Times">), |
| 582 |
and for the second argument it might also test objects of the classes </FONT><FONT FACE="Courier">PriorityQueue</FONT><FONT FACE="Times"> |
| 583 |
and </FONT><FONT FACE="Courier">FixedLengthQueue</FONT><FONT FACE="Times">, |
| 584 |
if these where derived from the </FONT><FONT FACE="Courier">Queue</FONT><FONT FACE="Times"> |
| 585 |
class.</FONT></FONT> |
| 586 |
|
| 587 |
<P><FONT SIZE=-1><FONT FACE="Times">The </FONT><FONT FACE="Courier">analyse</FONT><FONT FACE="Times"> |
| 588 |
method iterates through every possible combination of argument types and |
| 589 |
reports which variant (if any) would have been called for that set of arguments. |
| 590 |
Combinations that result in ambiguities or failure to dispatch are reported |
| 591 |
separately. Even more usefully, for argument sets where a single variant |
| 592 |
would be successfully dispatched, </FONT><FONT FACE="Courier">analyse</FONT><FONT FACE="Times"> |
| 593 |
also reports any other viable candidates (i.e. other variants that could |
| 594 |
handle the call, but which were at a greater inheritance distance from |
| 595 |
the argument list, and so not selected). This can be especially useful |
| 596 |
in determining why a particular variant was not called as expected.</FONT></FONT> |
| 597 |
<H2> |
| 598 |
Conclusion</H2> |
| 599 |
<FONT FACE="Times"><FONT SIZE=-1>Multiple dispatch is a specialized technique |
| 600 |
that handles a small but important class of problems where two or more |
| 601 |
objects drawn from different hierarchies must interact polymorphically. |
| 602 |
Although Perl doesn't provide an built-in multiple dispatch mechanism, |
| 603 |
one can be added to it.</FONT></FONT> |
| 604 |
|
| 605 |
<P><FONT FACE="Times"><FONT SIZE=-1>The Class::Multimethods module enables |
| 606 |
variants of a multimethod to be declared and used, either as object methods |
| 607 |
or as independent, overloaded subroutines. It provides a sophisticated |
| 608 |
breadth-first dispatch resolution mechanism and allows the implementor |
| 609 |
to dictate resolution strategies when dispatch would normally fail.</FONT></FONT> |
| 610 |
|
| 611 |
<P><FONT FACE="Times"><FONT SIZE=-1>The module is available from the <A HREF="http://www.perl.com/CPAN/authors/id/DCONWAY/">CPAN</A>.</FONT></FONT> |
| 612 |
<H2> |
| 613 |
<A NAME="references"></A>References</H2> |
| 614 |
|
| 615 |
<DIR> |
| 616 |
<OL> |
| 617 |
<LI> |
| 618 |
<FONT FACE="Times"><FONT SIZE=-1>Conway, D., <I><A HREF="http://www.manning.com/Conway/">Object |
| 619 |
Oriented Perl</A></I>, Chapter 13, Manning Publications, 1999.</FONT></FONT></LI> |
| 620 |
|
| 621 |
<LI> |
| 622 |
<FONT FACE="Times"><FONT SIZE=-1>Conway, D., <I>Multiple Dispatch in Perl,</I> |
| 623 |
<A HREF="http://www.tpj.com/">The Perl Journal</A> (to appear).</FONT></FONT></LI> |
| 624 |
|
| 625 |
<LI> |
| 626 |
<FONT FACE="Courier"><FONT SIZE=-1><A HREF="http://www.perl.com/CPAN/authors/id/DCONWAY/">http://www.perl.com/CPAN/authors/id/DCONWAY/</A></FONT></FONT></LI> |
| 627 |
</OL> |
| 628 |
</DIR> |
| 629 |
|
| 630 |
<HR> |
| 631 |
|
| 632 |
</BODY> |
| 633 |
</HTML> |