Is there a short circuit 'or' that returns the first 'true' value?

powershell, short-circuiting

Solution

You could do something like this:

10, $false, 20 | ? { $_ -ne $false } | select -First 1

The result is either the first value from the input list that isn't `$false`, or `$null`. Since `$null` is among the values that PowerShell treats as `$false` in comparisons, the above should do what you want.

Problem

Scheme has a short-circuiting `or` that will return the first non-false value: ``` > (or 10 20 30) 10 > (or #f 20 30) 20 > (or #f) #f ``` It does not evaluate its arguments until needed. Is there something like this already in PowerShell? Here's an approximation of it: ``` function or () { foreach ($arg in $args) { $val = & $arg; if ($val) { $val; break } } } ``` Example: ``` PS C:\> or { 10 } { 20 } { 30 } 10 ``` Example: ``` PS C:\> $abc = $null PS C:\> or { $abc } { 123 } 123 PS C:\> $abc = 456 PS C:\> or { $abc } { 123 } 456 ```

Original source

Related problems