Closures/Value capture: Difference between revisions
Content added Content deleted
(Added some comments to explain how we avoid the closure trap) |
(Add Axiom task) |
||
Line 3: | Line 3: | ||
'''Goal:''' To 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. |
'''Goal:''' To 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. |
||
=={{header|Axiom}}== |
|||
Using the Spad compiler: |
|||
<lang Axiom>)abbrev package TESTP TestPackage |
|||
TestPackage() : with |
|||
test: () -> List((()->Integer)) |
|||
== add |
|||
test() == [(() +-> i^2) for i in 1..10]</lang> |
|||
This can called from the interpreter using: |
|||
<lang Axiom>[x() for x in test()]</lang> |
|||
With output: |
|||
<lang Axiom>[1,4,9,16,25,36,49,64,81,100] |
|||
Type: List(Integer)</lang> |
|||
=={{header|C}}== |
=={{header|C}}== |