TheIronKnuckle
TheIronKnuckle

Reputation: 7294

Trying to get higher order functions to work in powershell

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.

Upvotes: 5

Views: 1680

Answers (3)

js2010
js2010

Reputation: 27516

Here's another way, getting into the less known features of foreach-object. It will run as many PROCESS scriptblocks as you give it, but the first and last have to be BEGIN and END blocks (like in awk). It works without the commas too.

1,2 | % $null, { $_ + $_ }, { $_ + 1}, {$_ - 1}, $null       

2
2
0
4
3
-1

Upvotes: 0

x0n
x0n

Reputation: 52450

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.

Upvotes: 8

BartekB
BartekB

Reputation: 8650

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.

Upvotes: 2

Related Questions