Closures/Value capture: Difference between revisions

Content added Content deleted
(simplify description)
m (added whitespace and highlighting to the task's preamble.)
Line 2: Line 2:


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


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


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.
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.
<br><br>


=={{header|Ada}}==
=={{header|Ada}}==