Corso di Raku / Programmazione funzionale, concorrente, reattiva e web / Programmazione funzionale / Lambda e chiusure / Exercises / Un contatore
Soluzione: Un contatore
Ecco una possibile soluzione del compito.
Codice
sub make-counter($step) {
my $n = 0;
return sub { $n += $step };
}
my &count = make-counter(10);
say count();
say count();
say count();🦋 Trova il programma nel file counter.raku.
Output
10
20
30Commenti
La chiusura cattura due cose da
make-counter: il parametro$stepe la variabile privata$n. Entrambe restano in vita dopo chemake-counterè ritornata.Ogni chiamata aggiunge
$stepa$ne restituisce il nuovo totale. Un contatore costruito con un passo diverso avanzerebbe invece di quella quantità.