@@ -336,7 +336,59 @@ The same effect could have been achieved with
336
336
To put a new operator on the same precedence level as an existing operator,
337
337
use C < is equiv(&other-operator) > instead.
338
338
339
- = comment TODO: is assoc
339
+
340
+ = head2 Associativity
341
+
342
+ When the same operator appears several times in a row, there are multiple
343
+ possible interpretation. For example
344
+
345
+ 1 + 2 + 3
346
+
347
+ could be parsed as
348
+
349
+ (1 + 2) + 3 # left associative
350
+
351
+ or as
352
+
353
+ 1 + (2 + 3) # right associative
354
+
355
+ or as single call to an operator with three operands
356
+
357
+ infix:<+>(1, 2, 3); # list associative
358
+
359
+ For addition of real numbers, the distinction is somewhat moot, because C < + > is
360
+ L < mathematically associative|https://en.wikipedia.org/wiki/Associative_property > .
361
+
362
+ But for other operators it matters a great deal. For example for the
363
+ exponentation/power operator, C << infix:<**> >> :
364
+
365
+ say 2 ** (2 ** 3); # 256
366
+ say (2 ** 3) ** 3; # 64
367
+
368
+ Perl 6 has the following possible associativity configurations:
369
+
370
+ = begin table
371
+
372
+ A Assoc Meaning of $a ! $b ! $c
373
+ = ===== =======================
374
+ L left ($a ! $b) ! $c
375
+ R right $a ! ($b ! $c)
376
+ N non ILLEGAL
377
+ C chain ($a ! $b) and ($b ! $c)
378
+ X list infix:<!>($a; $b; $c)
379
+
380
+ = end table
381
+
382
+ You can specify the associativity of an operator with the C < is assoc > trait,
383
+ where C < left > is the default associativity.
384
+
385
+ = begin code
386
+ sub infix:<§>(*@a) is assoc<list> {
387
+ '(' ~ @a.join('|') ~ ')';
388
+ }
389
+
390
+ say 1 § 2 § 3; # (1|2|3)
391
+ = end code
340
392
341
393
= head1 Traits
342
394
@@ -354,6 +406,9 @@ Examples of traits are:
354
406
has $another-attribute handles <close>;
355
407
# ^^^^^^^ trait
356
408
409
+ ... and also C < is tighter > , C < is looser > , C < is equiv > and C < is assoc > from the previous
410
+ section.
411
+
357
412
Traits are subs of the form C << trait_mod<VERB> >> , where C < VERB > stands for the
358
413
name like C < is > , C < does > or C < handles > . It receives the modified thing as
359
414
argument, and the name as a named argument.
0 commit comments