PowerShell equality operator not a symmetric relation?

前端 未结 4 405
面向向阳花
面向向阳花 2021-01-17 21:00

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
         


        
相关标签:
4条回答
  • 2021-01-17 21:03

    When you do "" -eq 0, it is same as "".equals(0) and it returns false.

    0 -eq "" will try to convert "" to in and [int]"" is 0 and hence you get true.

    0 讨论(0)
  • 2021-01-17 21:16

    My first guess is that in the first case, there is a conversion of the right hand operand from 0 to "0" (the type of the left hand operator being a string), therefore "" is not equal to "0". In the second case, there is a conversion from "" to int, and "" is considered as being 0.

    Try 3 + ""

    0 讨论(0)
  • 2021-01-17 21:27

    It is how PowerShell tries to convert the type and then compare.

    Check this:

    $false -eq ""
    

    This returns True as well.

    0 讨论(0)
  • 2021-01-17 21:28

    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.

    0 讨论(0)
提交回复
热议问题