I can't get this example to work
{ $_ + $_ }, { $_ + 1}, {$_ - 1} | % { $_ 1 }
I want it to construct a list/array/collection/whatever of functions (this part is fine), and then pipe that list to the code block on the right, which applies each of the functions to the argument 1 and returns an array with the results (namely; 2,2,0). I've tried using the getnewclosure() method, the & operator, nothing's worked so far.
The dollar underbar variable is an automatic variable that is only populated in certain scenarios; in this case, when there is an incoming object from the pipeline. In order to give the $_
the value of 1, which appears to be your intent, you'll have to pipe the number to each and also execute the scriptblock. The easiest way to do this is to pass it directly as an argument to %
(foreach-object
) which accepts a scriptblock:
PS> { $_ + $_ }, { $_ + 1}, {$_ - 1} | % { 1 | % $_ }
2
2
0
Look at it until it makes sense :) If it doesn't click, comment back here and I'll explain in more detail.
If you're interested in functional tinkering in powershell, you might enjoy this function I wrote for partial application:
http://www.nivot.org/blog/post/2010/03/11/PowerShell20PartialApplicationOfFunctionsAndCmdlets
It's a bit unwieldy, but still possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With