views:

217

answers:

2

Keith Hill explained me that blocks in PowerShell are not closures and that to create closures from blocks I have to call method .GetNewClosure().

Is there any elegant way to create closures from blocks? (e.g. create a wrapping function, an alias?, ...)

Example:

{ block }
${ closure } # ???
+2  A: 

Hi,

These links might be of some help they talk about closures in PowerShell 2.0

Alan
+3  A: 

You could create a function that takes a scriptblock, calls GetNewClosure and returns the closure. It is essential that you call this function using the dot operator e.g.:

function =>([scriptblock]$_sb_)
{
    $_sb_.GetNewClosure()
}

function A($block) 
{
    B (. => {Write-Host 2; &$block})
}

function B($block) {Write-Host 1;&$block}

A {Write-Host 3}

Not sure this is much better than just calling GetNewClosure() on the scriptblock though. Note you can pick some other name for the function. I was going for something more like C# lambdas.

Keith Hill
Thx. Why I need to use dot operator to call the function? (To get the same context?)
TN
Yes, so the function executes within the same scope it is called from.
Keith Hill
Keith, we really need to beat bruce and jeffrey into coming up with a more natural syntax. I hate the GetNewClosure() method. It's so clumsy. I was thinking using double braces: {{ $ix }} ?
x0n
Sounds good to me.
Keith Hill