@@ -179,15 +179,44 @@ which applies a function to each input element:
179
179
my @squared = map &square, 1..5;
180
180
say join ', ', @squared; # 1, 4, 9, 16, 25
181
181
182
- = comment e.g. `@list.sort :&as`, closures, lexical subs
183
182
184
- = comment return from sub and return from block
183
+ = head2 Closures
184
+
185
+ All code objects in Perl 6 are I < closures > , which means they can reference
186
+ lexical variables from an outer scope.
187
+
188
+ = begin code
189
+ sub generate-sub($x) {
190
+ my $y = 2 * $x;
191
+ return sub { say $y };
192
+ # ^^^^^^^^^^^^^^ inner sub, uses $y
193
+ }
194
+ my $generated = generate-sub(21);
195
+ $generated(); # 42
196
+ = end code
185
197
186
- = comment method invoke { ... }
198
+ Here C < $y > is a lexical variable inside C < generate-sub > , and the inner
199
+ subroutine that is returned uses it. By the time that the inner sub is called,
200
+ C < generate-sub > already has exited. Yet the inner sub can still use C < $y > ,
201
+ because it I < closed > over the variable.
202
+
203
+ A less obvious but useful example for closures is using L < map|/type/List#routine map >
204
+ to multiple a list of numbers:
205
+
206
+ my $multiply-by = 5;
207
+ say join ', ', map { $_ * $multiply-by }, 1..5; # 5, 10, 15, 20, 25
208
+
209
+ Here the block passed to C < map > references the variable C < $multiply-by > from
210
+ the outer scope, making the block a closure.
211
+
212
+ Languages without closures cannot easily provide higher-order functions that
213
+ are as easy to use and powerful as C < map > .
187
214
188
215
= head2 Routines
189
216
190
217
TODO
218
+ = comment return from sub and return from block
219
+
191
220
= comment Important ones: candidates, wrap, unwrap, assuming, arity, count
192
221
193
222
= comment link to Routine documentation (?)
0 commit comments