Task

Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index    i     (you may choose to start     i     from either    0    or    1),    when run, should return the square of the index,   that is,     i  2.

Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.



Goal

Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.

In imperative languages, one would generally use a loop with a mutable counter variable.

For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.

See also: Multiple distinct objects

' FB 1.05.0 Win64
 
Type Closure
  Private:
    index As Integer
  Public:
    Declare Constructor(index As Integer = 0)
    Declare Function Square As Integer 
End Type
 
Constructor Closure(index As Integer = 0)
   This.index = index
End Constructor
 
Function Closure.Square As Integer
   Return index * index
End Function
 
Dim a(1 To 10) As Closure
 
' create Closure objects which capture their index
For i As Integer = 1 To 10
  a(i) = Closure(i)
Next
 
' call the Square method on all but the last object
For i As Integer = 1 to 9
  Print a(i).Square
Next
 
Print
Print "Press any key to quit"
Sleep