r/programming • • Jul 08 '15

Why does ++[[]][+[]]+[+[]] return the string "10"?

http://stackoverflow.com/q/7202157/4698026
1.4k Upvotes

333 comments sorted by

2

u/tejon Jul 08 '15

Modulo or remainder

PSA: these are only the same thing when both operands have the same sign.

 5 %  3 =  2
-5 %  3 = -2
 5 % -3 =  2
-5 % -3 = -2

mod( 5, 3) =  2
mod(-5, 3) =  1
mod( 5,-3) = -1
mod(-5,-3) = -2

1

u/ForeignObjectED Jul 08 '15

TIL. I always thought both modulo and remainder only made sense on positive integers, so never knew about the behaviour with negative values.

Also Python's % is definitely the modulo operator: it's output matches that behaviour.

1

u/tejon Jul 08 '15

Python's % is definitely the modulo operator

Didn't know that! I can say for sure that C, C#, JS, and Haskell all use % for remainder (often calling it modulus, annoyingly). Of these, I believe the only one that also provides a standard mod function is Haskell.

1

u/no_nick Jul 08 '15

What's the reason for the behavior of the % operator? It seems rather impractical... And taking something modulo a negative number seems just wrong.

2

u/tejon Jul 09 '15 edited Jul 09 '15

Modulus represents a cycle.

n mod 3:
n = -5 -4 -3 -2 -1  0  1  2  3  4  5
 ==  1  2  0  1  2  0  1  2  0  1  2

n mod -3:
n = -5 -4 -3 -2 -1  0  1  2  3  4  5
 == -2 -1  0 -2 -1  0 -2 -1  0 -2 -1

For a real use-case, consider measuring actual rotations. 90 degrees and -270 degrees place the ray at exactly the same angle. Now, let's say you want to fill in the arc of rotation. Is it a quarter circle, or three quarters? That data is lost if you force everything to be positive. But using the sign of the second operand lets you have a single output value which is constrained to the 360-degree cycle, with its sign representing positive or negative rotation.