Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

I would like to suggest slightly different approach: use another automatic variable instead of $_, so that passed value (1) is used:

{ $args[0] + $args[0] }, { $args[0] + 1 },  { $args[0] - 1 } | % { & $_ 1 }

As Oisin mentioned, $_ is not used in: & { $_ } 1 scenario, it works only when pipeline is involved.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top