Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell equality operator not a symmetric relation?

Tags:

powershell

Can someone please explain to me why the equality operator in PowerShell is not a symmetric relation??

PS> "" -eq 0
False
PS> 0 -eq ""
True
like image 738
Nacht Avatar asked Apr 17 '12 05:04

Nacht


1 Answers

Yes, -eq in PowerShell is not an equivalence relation. While theorists may cry out in terror at this point it's mostly to make the language better at conveying ideas and simpler to understand.

For example, PowerShell always tries converting differing types in binary operators to the type of the left operand which is why you see the behaviour in your question. In practice I have found this to be rarely a problem, except in contrived examples. In my own data I usually write comparisons with matching types and when working with other data the conversions are usually not harmful in that they detroy the meaning. And this is a case where I think predictability of the language is more important than attaining a mathematical ideal (which isn't even attainable everywhere anyway given that numbers in computers are only approximations of mathematical entities).

Another thing is that if the left operand of a comparison operator (-eq, -gt, -lt, -ge, -le, -match, ...) is a collection, then the operator returns all items of the collection where the operator would yield true. This would be a case where you can quickly filter a collection without needing a where, but I guess the real advantage is that you can write the conditional if ($foo -gt 4) which then can mean both »if $foo is a scalar value larger than 4« or »if $foo is a collection containing items larger than 4« without needing to stick a pipeline into the if.

like image 110
Joey Avatar answered Oct 05 '22 04:10

Joey