my $block = { say "I'm a block with topic $_" };
$block('x');
my $pointy = -> $a, $b { $a + $b }; # pointy block = lambda with a signature
say $pointy(2, 3);
my $typed = -> Int $n --> Int { $n * 2 };
for <a b c>.kv -> $i, $v { }
15.2 Placeholder Variables
my $sum = { $^a + $^b }; # placeholders sort alphabetically: $^a then $^b
say $sum(10, 5); # 15
say (5, 3, 8).sort({ $^b <=> $^a }); # descending: (8 5 3)
my $named = { "Hello, $:name" };
say $named(name => 'Ana');
15.3 Whatever Star and WhateverCode
say (1..10).grep(* > 5); # * > 5 is a WhateverCode (closure)
say (1..5).map(* * 2); # (2 4 6 8 10)
say (1..6).map(* + *); # each * is a separate parameter, so map takes 2 at a time: (3 7 11)
my &add = * + *;
say add(3, 4); # 7
say <apple fig kiwi>.sort(*.chars); # method call on Whatever
say <apple fig kiwi>.map(*.uc);
my @a = 1..10;
say @a[*-1], ' ', @a[*-3..*-1]; # * in subscripts = number of elements
say (1, 2, 3).map(&[+].assuming(10)); # partial application: (11 12 13)
say <a b c>.map(* x 2); # (aa bb cc)
15.4 Closures
sub make-counter(Int $start = 0) {
my $count = $start;
return { $count++ };
}
my &c1 = make-counter();
my &c2 = make-counter(10);
say c1(), c1(), c2(); # 0 1 10
sub make-adder($n) { -> $x { $x + $n } }
my &add5 = make-adder(5);
say add5(10); # 15
say (1..3).map(make-adder(100)); # (101 102 103)