Skip to content

Commit

Permalink
Explain closures a bit
Browse files Browse the repository at this point in the history
  • Loading branch information
moritz committed Jan 31, 2015
1 parent c2be389 commit 4105b6f
Showing 1 changed file with 32 additions and 3 deletions.
35 changes: 32 additions & 3 deletions lib/Language/functions.pod
Original file line number Diff line number Diff line change
Expand Up @@ -179,15 +179,44 @@ which applies a function to each input element:
my @squared = map &square, 1..5;
say join ', ', @squared; # 1, 4, 9, 16, 25
=comment e.g. `@list.sort :&as`, closures, lexical subs
=comment return from sub and return from block
=head2 Closures
All code objects in Perl 6 are I<closures>, which means they can reference
lexical variables from an outer scope.
=begin code
sub generate-sub($x) {
my $y = 2 * $x;
return sub { say $y };
# ^^^^^^^^^^^^^^ inner sub, uses $y
}
my $generated = generate-sub(21);
$generated(); # 42
=end code
=comment method invoke { ... }
Here C<$y> is a lexical variable inside C<generate-sub>, and the inner
subroutine that is returned uses it. By the time that the inner sub is called,
C<generate-sub> already has exited. Yet the inner sub can still use C<$y>,
because it I<closed> over the variable.
A less obvious but useful example for closures is using L<map|/type/List#routine map>
to multiple a list of numbers:
my $multiply-by = 5;
say join ', ', map { $_ * $multiply-by }, 1..5; # 5, 10, 15, 20, 25
Here the block passed to C<map> references the variable C<$multiply-by> from
the outer scope, making the block a closure.
Languages without closures cannot easily provide higher-order functions that
are as easy to use and powerful as C<map>.
=head2 Routines
TODO
=comment return from sub and return from block
=comment Important ones: candidates, wrap, unwrap, assuming, arity, count
=comment link to Routine documentation (?)
Expand Down

0 comments on commit 4105b6f

Please sign in to comment.