How to resolve the algorithm Closures/Value capture step by step in the Icon and Unicon programming language
How to resolve the algorithm Closures/Value capture step by step in the Icon and Unicon programming language
Table of Contents
Problem Statement
Create a list of ten 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 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
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. See also: Multiple distinct objects
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Closures/Value capture step by step in the Icon and Unicon programming language
Source code in the icon programming language
procedure main(args) # Closure/Variable Capture
every put(L := [], vcapture(1 to 10)) # build list of index closures
write("Randomly selecting L[",i := ?*L,"] = ",L[i]()) # L[i]() calls the closure
end
# The anonymous 'function', as a co-expression. Most of the code is standard
# boilerplate needed to use a co-expression as an anonymous function.
procedure vcapture(x) # vcapture closes over its argument
return makeProc { repeat { (x[1]^2) @ &source } }
end
procedure makeProc(A) # the makeProc PDCO from the UniLib Utils package
return (@A[1], A[1])
end
You may also check:How to resolve the algorithm Constrained genericity step by step in the E programming language
You may also check:How to resolve the algorithm Super-d numbers step by step in the Phix programming language
You may also check:How to resolve the algorithm Subleq step by step in the SETL programming language
You may also check:How to resolve the algorithm Loops/N plus one half step by step in the Phix programming language
You may also check:How to resolve the algorithm Call a function step by step in the LFE programming language