15 lines
1.1 KiB
Plaintext
15 lines
1.1 KiB
Plaintext
;Task:
|
|
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index <big> ''<b> i </b>'' </big> (you may choose to start <big> ''<b> i </b>'' </big> from either <big> '''0''' </big> or <big> '''1'''), </big> when run, should return the square of the index, that is, <big> ''<b> i </b>'' <sup>2</sup>.</big>
|
|
|
|
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]]
|