Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: an elegant way to create closures

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 } # ???
like image 920
TN. Avatar asked Dec 02 '09 10:12

TN.


1 Answers

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.

like image 148
Keith Hill Avatar answered Sep 22 '22 10:09

Keith Hill