6.8 Multiple Dispatch

     

In the previous chapter, we mentioned multi subroutines. The multi keyword actually applies to any code object: subroutines, methods , or submethods . As we said before, multi allows you to define multiple, different routines all with the same name but different signatures. This example dispatches to a variant of the lunch method depending on the types of the arguments:

 multi method lunch (Lunching::Friar $who, Megadodo::Office $location) {     print "Jolly nice restaurant."; } multi method lunch (Hitchhiker $who, Cargo::Hold $location) {     print "Towel again."; } 

A member of the Lunching Friars of Voondon must always eat at a nice restaurant when he visits the offices of Megadodo Publications. A hitchhiker in a cargo hold, however, will just have to settle for the nutrient solution soaked into the corner of his towel.

A call to a multimethod has the same syntax as a call to a subroutine ”the name of the routine followed by a list of arguments:

 lunch($zaphod, $where); 

This call searches outward through its lexical, package, and global scopes for a matching name. If it finds a nonmulti sub it makes an ordinary subroutine call. Otherwise, it generates a list of multi subs, methods, or submethods with that name and dispatches to the closest matching signature.(For more complete details on the dispatch process, see Apocalypse 12.)

You can also call a multimethod with an ordinary single-dispatch method call:

 $zaphod.lunch($where); 

In this case, the call will only failover to multiple dispatch if it can't find a suitable method to call under single dispatch to $zaphod .

6.8.1 Operator Overloading

Operator overloading makes use of multiple dispatch. An operator is just a subroutine with special call syntax. Operators define the kind of syntax they use as part of their name: prefix , postfix , infix , circumfix , etc. This example overloads two operators that use the + symbol ”one prefix operator and one infix operator:

 multi sub *prefix:+ (Time $a) { . . . }         # $x = +$y; multi sub *infix:+ (Time $a, Time $b) { . . . } # $x = $y + $z; 

These operators are declared as multi subs with global scope, as most operators will be in Perl 6 (global is specified by the leading * in the name). They're multi, so it's easy to add new behavior for new types of operands. They're global so that any operation anywhere with the defined operand types will find the right multi variant of the operator.



Perl 6 and Parrot Essentials
Perl 6 and Parrot Essentials, Second Edition
ISBN: 059600737X
EAN: 2147483647
Year: 2003
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net