Why does the Rem operator in Elixir return negative numbers?

I am trying a simple operation

rem(-1, 25)

      

I expect this to be a reminder of integer division and return 24 (same as in Ruby), but it returns -1. Am I doing something wrong? Is the behavior broken on the elixir?

+3


source to share


3 answers


The remainder sign actually changes for every programming language: https://en.wikipedia.org/wiki/Modulo_operation . So both are correct and both are wrong. :)



+7


source


Ruby:

irb > -1.remainder(25) 
 => -1 

      

Elixir:

iex(6)> rem(-1,25)
-1

      



They work the same way.

But I think you mean modulo from Ruby:

irb > -1.modulo(25)
 => 24

      

If you want a function that behaves like this, I think you need to write your own here .

+6


source


In the words of Davis Thomas in Elixir Programming:

rem is the remainder operator. It is called a function (rem (11, 3) => 2). This differs from the usual modulo operations in that the result will have the same sign as the first argument of the functions.

This means that in your case, which is rem (-1, 25), the result will have a - sign, just like the first arg.

+3


source







All Articles