Closures/Value capture: Difference between revisions
Content added Content deleted
(Added Elixir) |
(simplify description) |
||
Line 2: | Line 2: | ||
;Task: |
;Task: |
||
Create a list of |
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>. |
||
Display the result of running any but the last function, |
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. |
||
Line 12: | 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, |
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}}== |