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

A counter

Problem

Write a subroutine make-counter($step) that returns a closure. Each time the closure is called, it advances a running total by $step and returns it. The closure must remember both the step and the total. Create a counter with a step of 10 and print its first three values.

Example

The program prints:

10
20
30

Solution

See the solution

Course navigation

Quiz — Closures   |   Solution: A counter