How to resolve the algorithm Closures/Value capture step by step in the PowerShell programming language
How to resolve the algorithm Closures/Value capture step by step in the PowerShell 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 PowerShell programming language
Source code in the powershell programming language
function Get-Closure ([double]$Number)
{
{param([double]$Sum) return $script:Number *= $Sum}.GetNewClosure()
}
for ($i = 1; $i -lt 11; $i++)
{
$total = Get-Closure -Number $i
[PSCustomObject]@{
Function = $i
Sum = & $total -Sum $i
}
}
$numbers = 1..20 | Get-Random -Count 10
foreach ($number in $numbers)
{
$total = Get-Closure -Number $number
[PSCustomObject]@{
Function = $number
Sum = & $total -Sum $number
}
}
You may also check:How to resolve the algorithm Random sentence from book step by step in the Wren programming language
You may also check:How to resolve the algorithm URL decoding step by step in the Maple programming language
You may also check:How to resolve the algorithm Klarner-Rado sequence step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm Hello world/Text step by step in the LiveCode programming language
You may also check:How to resolve the algorithm Prime conspiracy step by step in the Rust programming language