Codele / Advanced programming
Functions as values and closures
A function can be stored in a variable, handed to other code and returned, like a number. A function made inside another one even remembers the variables that were around when it was made.
- A function is a value. You can store it in a variable (a = make_counter()), pass it to another function and return it from one.
- A closure is a function that remembers the variables that were around when it was made. Each call to make_counter gives a new function with its own count.
- Python needs the word nonlocal so press may change count. Java is stricter: a lambda cannot change a local variable, so we hide the count in a one-slot array. Python, JavaScript, C# and Go share the variable itself; Java and C++ copy its value in.
- C++ must say what a lambda keeps. [count] copies the box in, and mutable allows the copy to change. Capturing by reference would point at a box that has already vanished.
Loading the playable lesson…