-
Notifications
You must be signed in to change notification settings - Fork 292
/
WhateverCode.pod6
64 lines (46 loc) · 1.84 KB
/
WhateverCode.pod6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
=begin pod
=TITLE class WhateverCode
=SUBTITLE Code object constructed by Whatever-currying
class WhateverCode is Code { }
C<WhateverCode> objects are the result of L<Whatever>-currying. See the
L<Whatever> documentation for details.
When you wish to control how a method or function interprets any
I<Whatever stars>, you may use multi dispatch with C<Whatever> and
C<WhateverCode> parameters to do so, as in the following example:
class Cycle {
has $.pos;
has @.vals;
}
multi sub get-val(Cycle $c, Int $idx) {
$c.vals[$idx % $c.vals.elems]
}
# Define what to do with a stand-alone * as the second argument
multi sub get-val(Cycle $c, Whatever $idx) {
get-val($c, $c.pos);
}
# Define what to do with a * WhateverCode in an expression
multi sub get-val(Cycle $c, WhateverCode $idx) {
get-val($c, $idx($c.pos));
}
my Cycle $c .= new(:pos(2), :vals(0..^10));
say get-val($c, 3); # OUTPUT: «3»
say get-val($c, *); # OUTPUT: «2»
say get-val($c, *-1); # OUTPUT: «1»
The C<WhateverCode> C<does> L<Callable> role, so it's possible to introspect
the type of C<Callable> it contains. Continuing the previous
example, we can add a multi that handles a C<WhateverCode> with two arguments:
=begin code :skip-test
# Define what to do with two * in an expression
multi sub get-val(Cycle $c, WhateverCode $idx where { .arity == 2 }) {
get-val($c, $idx($c.pos, $c.vals.elems));
}
say get-val($c, * + * div 2); # 2 + 10/2 = 7
=end code
Note, though, that subexpressions may impose their own I<Whatever star>
rules:
=for code :skip-test
my @a = (0, 1, 2);
say get-val($c, @a[*-1]) # 2, because the star belongs to the Array class
This can make the ownership of I<Whatever stars> become confusing rather
quickly, so be careful not to overdo it.
=end pod