Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 237 lines (168 sloc) 8.845 kB
68d062f Move synopses to their new home.
pmichaud authored
1 =encoding utf8
2
3 =head1 TITLE
4
5 Synopsis 13: Overloading
6
04840a3 [Spec] treat all authors equally
lwall authored
7 =head1 AUTHORS
68d062f Move synopses to their new home.
pmichaud authored
8
04840a3 [Spec] treat all authors equally
lwall authored
9 Larry Wall <larry@wall.org>
68d062f Move synopses to their new home.
pmichaud authored
10
11 =head1 VERSION
12
04840a3 [Spec] treat all authors equally
lwall authored
13 Created: 2 Nov 2004
14
15 Last Modified: 27 Dec 2008
16 Version: 12
68d062f Move synopses to their new home.
pmichaud authored
17
18 =head1 Overview
19
20 This synopsis discusses those portions of Apocalypse 12 that ought to have
21 been in Apocalypse 13.
22
23 =head1 Multiple dispatch
24
25 The overloading mechanism of Perl 5 has been superseded by Perl 6's
26 multiple dispatch mechanism. Nearly all internal functions
27 are defined as C<multi> subs or C<multi> methods on generic types.
28 Built-in operators are merely oddly named functions with an alternate
29 call syntax. All you have to do to overload them is to define your
30 own C<multi> subs and methods that operate on arguments with more
31 specific types.
32
33 For unary operators, this makes little effective difference, but for
34 binary operators, multiple dispatch fixes the Perl 5 problem of paying
35 attention only to the type of the left argument. Since both argument
36 types are used in deciding which routine to call, there is no longer
37 any trickery involving swapping the arguments to use the right argument's
38 type instead of the left one. And there's no longer any need to
39 examine a special flag to see if the arguments were reversed.
40
41 For much more about multiple dispatch, see S12.
42
43 =head1 Syntax
44
45 There is no longer any special C<use overload> syntax separate from the
46 declarations of the C<multi> routines themselves. To overload an
47 existing built-in sub, say something like:
48
afbd198 [Spec] get rid of some fossil uses of * spotted by masak++
lwall authored
49 multi sub uc (TurkishStr $s) {...}
68d062f Move synopses to their new home.
pmichaud authored
50
afbd198 [Spec] get rid of some fossil uses of * spotted by masak++
lwall authored
51 A multi is automatically exported if goverened by a proto that is exported.
52 It may also be explicitly exported:
53
54 multi sub uc (TurkishStr $s) is exported {...}
55
56 Now if you call C<uc()> on any Turkish string, it will call your
57 function rather than the built-in one.
68d062f Move synopses to their new home.
pmichaud authored
58
59 The types of the parameters are included in the I<longname> of any C<multi>
60 sub or method. So if you want to overload string concatenation for Arabic
61 strings so you can handle various ligatures, you can say:
62
afbd198 [Spec] get rid of some fossil uses of * spotted by masak++
lwall authored
63 multi sub infix:<~>(ArabicStr $s1, ArabicStr $s2) {...}
64 multi sub infix:<~>(Str $s1, ArabicStr $s2) {...}
65 multi sub infix:<~>(ArabicStr $s1, Str $s2) {...}
68d062f Move synopses to their new home.
pmichaud authored
66
67 The C<use overload> syntax had one benefit over Perl 6's syntax in that
68 it was easy to alias several different operators to the same service
69 routine. This can easily be handled with Perl 6's aliasing:
70
71 multi sub unimpl (MyFoo $x, MyFoo $y) { upchuck(); }
72 &infix:<+> ::= &unimpl;
73 &infix:<-> ::= &unimpl;
74 &infix:<*> ::= &unimpl;
75 &infix:</> ::= &unimpl;
76
77 That's one solution, but often your alternatives all have the same
78 name, and vary instead in their signature. Some operators are
79 commutative, or can otherwise take their arguments in more than
80 one order. Perl allows you to declare multiple signatures for a
81 given body, and these will be pattern matched as if you had declared
82 separate multi entries. If you say:
83
84 multi sub infix:<+> (Us $us, Them $them) |
85 (Them $them, Us $us) { myadd($us,$them) }
86
87 that's equivalent to:
88
89 multi sub infix:<+> (Us $us, Them $them) { myadd($us,$them) }
90 multi sub infix:<+> (Them $them, Us $us) { myadd($us,$them) }
91
92 except that there really is only one body. If you declared a C<state>
93 variable within the body, for instance, there would only be one
94 of them.
95
afbd198 [Spec] get rid of some fossil uses of * spotted by masak++
lwall authored
96 A multi is in effect only within the scope in which it is defined or
97 imported. Generally you want to put your multi subs into a package
98 that will be imported wherever they are needed.
68d062f Move synopses to their new home.
pmichaud authored
99
100 When you use the multiple signature syntax, the alternate signatures
101 must all bind the same set of formal variable names, though they
102 are allowed to vary in any other way, such as by type, or by which
103 parameters are considered optional or named-only or slurpy. In other
104 words, the compiler is allowed to complain if any of the alternatives
105 omits any of the variable names. This is intended primarily to catch
106 editing errors.
107
108 Conjectural: If the first parameter to a multi signature is followed
109 by an invocant colon, that signature represents two signatures, one
110 for an ordinary method definition, and one for the corresponding multi
111 definition that has a comma instead of the colon. This form is legal
112 only where the standard method definition would be legal, and only
113 if any declared type of the first parameter is consistent with $?CLASS.
114
115 =head1 Fallbacks
116
117 Dispatch is based on a routine's signature declaration without regard
118 to whether the routine is defined yet. If an attempt is made to
119 dispatch to a declared but undefined routine, Perl will redispatch
120 to an C<AUTODEF> submethod [conjectural] as appropriate to define the routine. This provides
121 a run-time mechanism for fallbacks. By default, these declarations
122 are taken at face value and do not specify any underlying semantics.
123 As such, they're a "shallow" interpretation.
124
125 However, sometimes you want to specify a "deep" interpretation of
126 your operators. That is, you're specifying the abstract operation,
127 which may be used by various shallow operators. Any deep multi
128 declarations will be "amplified" into all the shallow operators that
129 can be logically based on it. If you say:
130
131 multi sub infix:<%> (Us $us, Them $them) is deep { mymod($us,$them) }
132
133 then
134
135 multi sub infix:<%=> (Us $us, Them $them) { $us = $us % $them }
136
137 is also generated for you (unless you define it yourself).
138 The mappings of magical names to sub definitions is controlled by the
139 C<%?DEEPMAGIC> compiler hash. Pragmas can influence the contents of
140 this hash over a lexical scope, so you could have different policies
141 on magical autogeneration. The default mappings correspond to the
142 standard fallback mappings of Perl 5 overloading.
143
144 These deep mappings are mainly intended for infix operators that would have
145 difficulty naming all their variants. Prefix operators tend to be simpler;
146 note in particular that
147
148 multi prefix:<~> is deep {...}
149
150 is better written:
151
152 method Str {...}
153
154 (see below).
155
156 =head1 Type Casting
157
158 A class may define methods that allow it to respond as if it were a
159 routine, array, or hash. The long forms are as follows:
160
161 method postcircumfix:<( )> ($capture) {...}
162 method postcircumfix:<[ ]> (*@@slice) {...}
163 method postcircumfix:<{ }> (*@@slice) {...}
164
165 Those are a bit unwieldy, so you may also use these short forms:
166
167 method &.( $capture ) {...}
168 method @.[ *@@slice ] {...}
169 method %.{ *@@slice } {...}
170
171 The sigil-dot sequence in these short forms autogenerates the
172 corresponding public operators, in exactly the same way that
173 the sigil-dot in:
174
175 has $.action;
176 has @.sequence;
177 has %.mapping;
178
179 autogenerates public accessor methods.
180
181 And because it uses the same method-autogeneration mechanism, the
182 specific sigil used to specify a short-form postcircumfix operator
183 doesn't actually matter...as long as it's followed by a dot and the
184 bracket pair containing the signature. (Though it's probably kinder
185 to future readers of your code to stick with the "natural" sigil
186 for each type of bracket.)
187
188 Note that the angle bracket subscripting form C<< .<a b c> >>
189 automatically translates itself into a call to C< .{'a','b','c'} >,
190 so defining methods for angles is basically useless.
191
192 The expected semantics of C<&.()> is that of a type coercion which may
193 or may not create a new object. So if you say:
194
195 $fido = Dog.new($spot)
196
197 it certainly creates a new C<Dog> object. But if you say:
198
199 $fido = Dog($spot)
200
201 it might call C<Dog.new>, or it might pull a C<Dog> with Spot's
202 identity from the dog cache, or it might do absolutely nothing if
203 C<$spot> already knows how to be a C<Dog>. As a fallback, if no
204 method responds to a coercion request, the class will be asked to attempt to
205 do C<Dog.new($spot)> instead.
206
207 It is also possible (and often preferable) to specify coercions from
208 the other end, that is, for a class to specify how to coerce one of
209 its values to some other class. If you define a method whose name
210 is a declared type, it is taken as a coercion to that type:
211
212 method Str { self.makestringval() }
213
214 As with all methods, you can also export the corresponding multi:
215
216 method Str is export { self.makestringval() }
217
218 in which case you can use both calling forms:
219
220 $x.Str
221 Str($x)
222
223 If the source class and the destination class both specify a
224 coercion routine, the ambiguity is settled by the ordinary rules
225 of multiple dispatch. Usually the source class will have the more
226 specific argument and will win; ties are also possible, and those
227 calls will fail. Additional arguments may sway the dispatch one way
228 or the other depending on the candidate list.
229
230 Note that, because the name of an anonymous class is unknown, coercion to
231 an anonymous class can only be specified by the destination class:
232
233 $someclass = generate_class();
234 $someclass($x);
235
236 =for vim:set expandtab sw=4:
Something went wrong with that request. Please try again.