Closures/Value capture: Difference between revisions

m
added a ;Task: and ;Goal: (bold) headers, added other whitespace to the task's preamble.
m (added a ;Task: and ;Goal: (bold) headers, added other whitespace to the task's preamble.)
Line 1:
{{task}}
 
'''Task:''' Create a list of 10 functions, in the simplest manner possible
;Task:
(anonymous functions are encouraged), such that the function at index <math>i</math>
'''Task:''' Create a list of 10 functions, in the simplest manner possible
(you may choose to start <math>i</math> from either 0 or 1), when run,
should(anonymous returnfunctions theare squareencouraged), ofsuch that the index,function thatat is,index &nbsp; <big><math> i^2 </math>.</big> &nbsp;
(you may choose to start &nbsp; <big><math> i </math></big> &nbsp; from either 0 or 1), when run,
should return the square of the index, that is, &nbsp; <big><math>i^2</math></big>.
 
Display the result of running any but the last function,
to demonstrate that the function indeed remembers its value.
 
 
;Goal:
'''Goal:''' To demonstrateDemonstrate 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.