Closures/Value capture: Difference between revisions

Content added Content deleted
m (added whitespace and highlighting to the task's preamble, used a larger font to show the expressions so that the italics and superscripts are easier to read.)
Line 2: Line 2:


;Task:
;Task:
Create a list of &nbsp; '''10''' &nbsp; functions, &nbsp; in the simplest manner possible &nbsp; (anonymous functions are encouraged), &nbsp; such that the function at index &nbsp; <big><big><math> i </math></big></big> &nbsp; (you may choose to start &nbsp; <big><big><math> i </math></big></big> &nbsp; from either &nbsp; '''0''' &nbsp; or &nbsp; '''1'''), &nbsp; when run, &nbsp; should return the square of the index, &nbsp; that is, &nbsp; <big><big><math> i^2</math></big></big>.
Create a list of 10 functions, in the simplest manner possible
(anonymous functions are encouraged), such that the function at index &nbsp; <big><math> i </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,
Display the result of running any but the last function, &nbsp; to demonstrate that the function indeed remembers its value.
to demonstrate that the function indeed remembers its value.




Line 16: Line 12:
In imperative languages, one would generally use a loop with a mutable counter variable.
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''
For each function to maintain the correct number, &nbsp; it has to capture the &nbsp; ''value'' &nbsp; of the variable at the time it was created, &nbsp; rather than just a reference to the variable, &nbsp; which would have a different value by the time the function was run.
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.
<br><br>
<br><br>