Skip to content

Commit 4105b6f

Browse files
committed
Explain closures a bit
1 parent c2be389 commit 4105b6f

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

lib/Language/functions.pod

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -179,15 +179,44 @@ which applies a function to each input element:
179179
my @squared = map &square, 1..5;
180180
say join ', ', @squared; # 1, 4, 9, 16, 25
181181
182-
=comment e.g. `@list.sort :&as`, closures, lexical subs
183182
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
185197
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>.
187214
188215
=head2 Routines
189216
190217
TODO
218+
=comment return from sub and return from block
219+
191220
=comment Important ones: candidates, wrap, unwrap, assuming, arity, count
192221
193222
=comment link to Routine documentation (?)

0 commit comments

Comments
 (0)