Wednesday, May 23, 2018

FP = Functional PowerShell

I have been writing a lot of F# the last few years, and this has made me look critically at some of my PowerShell scripts. While we may use pipelines all the time in PowerShell, often we still treat it as yet-another-curly-bracket-language when it comes to flow control.

But this is our preconceptions letting is down, because PowerShell is already much more expression orientated than that. So, for example, 'if' and 'switch' in PowerShell are (since v2 or something) expressions, and not just pure imperative branching.

This means that - rather than write this:

# imperative version
if ($inputValue % 2 -eq 0){
    $result_a = 'even'
}else{
    $result_a = 'odd'
}
Write-Host "Result_A is now $result_A"
... you could instead write the far superior:

# expression-orientated version
$result_b = `
    if ($inputValue % 2 -eq 0){
        'even'
    }else{
        'odd'
    }

Write-Host "Result_B is now $result_b"
This works with 'switch' also:

# expression-orientated switch version
$c = `
    switch($inputValue){
        1 { 'One' }
        2 { 'Two' }
        default { 'Other' } 
    }

Write-Host "C is now $c"
Sure, PowerShell isn't going to give you any nice warnings about not providing output values on all branches and so forth, but the latter version is just plain *easier to follow*.

No comments:

Popular Posts