Course of Raku / Functional, concurrent, reactive, and web programming / Functional programming / Lambdas and closures / Closures

Quiz — Closures

What does the following program print?

sub make-acc {
    my $total = 0;
    return sub ($x) { $total += $x };
}

my &add = make-acc;
add(10);
add(20);
say add(5);
05
030
135
00

The returned subroutine closes over $total, so all three calls share the same variable. The first two calls bring it to 30; the third adds 5 and prints the running total, 35.

Course navigation

Closures   |   A counter