Hacker News new | ask | show | jobs
by zasdffaa 1421 days ago
> (a + b) => (b + a)

> Semantically the query hasn’t changed

Now hang on a minute. Extend that to 3 and it can be (mssql but true in any I guess):

   declare @hi int =  2147483647;
   declare @lo int = -2147483648;

   declare @x int = @hi + @lo + @hi;  -- ok

   declare @y int = @hi + @hi + @lo; -- 'Arithmetic overflow error'
Worse yet with floats. I see what you're saying and good stuff, I'm thinking about this myself and I appreciate this article and will read it properly, but the edge cases have to be acknowledged.

Edit: this kind of thing is apparently something compiler writers keep rediscovering the hard way.

1 comments

Associativity and communtativity are different things.

@hi + @lo + @hi means (@hi + @lo) + @hi

@hi + @hi + @lo means (@hi + @hi) + @lo

Just because you can write this without the parentheses does not mean you can ignore them. To get from one to the other need not just the commutativity rule relied on by the diffing algorithm but also the associativity rule:

(@hi + @lo) + @hi =assoc=> @hi + (@lo + @hi) =comm=> @hi + (@hi + @lo) =assoc=> (@hi + @hi) + @lo

Here the third (associativity) change introduces the overflow, not the commutativity change which should always be safe for both integers and floating point numbers.

You're right but I'm just making the point that machine arithmetic ain't number arithmetic and you can't rearrange freely.

His example included SUM(b + c) and SUM(c + b) as equivalent. As such it probably is[1] but extend it to 3 numbers and you can't rearrange, as I think we agree.

[1] assuming b and c are numbers not strings, as + is string concat in some dialects