Powershell is equivalent to F # Seq.forall

I wrote this (which works):

function ForAll { BEGIN { $allTrue = $true } PROCESS { if ($_ -lt 1) { $allTrue = $false } } END { $allTrue } } $aList = (0..4) $bList = (1..4) $aList | ForAll # returns false $bList | ForAll # returns true 

But I want to replace ($ _ -lt 1) with a function called something like the $ predicate that I pass to the ForAll function. I can't seem to get this to work. Any ideas?

+4
source share
3 answers

Use [scriptblock], imho, it is much simpler than using functions here. It was a scripting task.

 function ForAll([scriptblock]$predicate) { BEGIN { $allTrue = $true } PROCESS { if (!(& $predicate $_)) { $allTrue = $false } } END { $allTrue } } $aList = (0..4) $bList = (1..4) $aList | ForAll {$args[0] -le -10 } # returns false $bList | ForAll {$args[0] -le 10 } # returns true 

$ args [0] denotes the first argument passed to the script block - in this case, it is $ _.

+3
source

If you use PowerShell 2.0, you can use a parameter with a script block to declare parameters, for example:

 function ForAll { param( [Parameter(Position=0,Mandatory=$true)] [scriptblock] $Expression, [Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true)] [psobject] $InputObject ) Begin { $allTrue = $true } Process { foreach ($obj in $InputObject) { if (!(&$Expression $obj)) { $allTrue = $false } } } End { $allTrue } } $aList = (0..4) $bList = (1..4) ForAll {param($val) $val -gt 0} (0..4) # returns false $aList | ForAll {param($val) $val -gt 0} # returns false $bList | ForAll {param($val) $val -gt 0} # returns true $aList | ForAll {param($val) $val -ge 0 -and $val -le 4} # returns true 
+3
source

For efficient processing, we will use a filter instead of a function, and we will β€œbreak” as soon as we detect a false element. It also stops all upstream processes:

 filter ForAll([scriptblock] $predicate) { PROCESS { if ( @($_ | Where-Object $predicate).Length -eq 0 ) { $false; break; } } END { $true; } } 

Use it idiomatically:

 (0..4) | ForAll { $_ -gt 0 } # returns false (1..4) | ForAll { $_ -gt 0 } # returns true 
0
source

All Articles