@@ -91,9 +91,60 @@ Calculating 43th prime
91
91
191
92
92
= end code
93
93
94
+ = head2 trait is pure
95
+
96
+ multi sub trait_mod:<is>(Routine $r, :!$pure)
97
+
98
+ Marks a subroutine as I < pure > , that is, it asserts that for the same input, it
99
+ will always produce the same output without any additional side effects.
100
+
101
+ This is a hint to the compiler that it can constant-fold calls to such
102
+ functions when the arguments are known at compile time.
103
+
104
+ sub double(Numeric:D $x) is pure {
105
+ 2 * $x;
106
+ }
107
+
108
+ = head2 trait is rw
109
+
110
+ multi sub trait_mod:<is>(Routine $r, :!$rw)
111
+
112
+ When a routine is modifies with this trait, its return value will be writable.
113
+ This is useful when returning variables or writable elements of hashes or
114
+ arrays, for example:
115
+
116
+ = begin code
117
+ sub walk(\thing, *@keys) is rw {
118
+ my $current := thing;
119
+ for @keys -> $k {
120
+ if $k ~~ Int {
121
+ $current := $current[$k];
122
+ }
123
+ else {
124
+ $current := $current{$k};
125
+ }
126
+ }
127
+ $current;
128
+ }
129
+
130
+ my %hash;
131
+ walk(%hash, 'some', 'key', 1, 2) = 'autovivified';
132
+
133
+ say %hash.perl;
134
+ = end code
135
+
136
+ produces
137
+
138
+ = begin code
139
+ ("some" => {"key" => [Any, [Any, Any, "autovivified"]]}).hash
140
+ = end code
141
+
142
+ Note that C < return > marks return values as read only; if you need an early
143
+ exit from an C < is rw > routine, you have to use C < return-rw > instead.
144
+
94
145
= begin comment
95
146
96
- TODO: traits hidden_from_backtrace, pure, export, rw , DEPRECATED
147
+ TODO: traits hidden_from_backtrace, export, DEPRECATED
97
148
98
149
= end comment
99
150
0 commit comments