How do I use the modulo operator in Elixir?
For example in Ruby you can do:
5 % 2 == 0
How does it differ from Ruby's modulo operator?
For non-negative integers, use Kernel.rem/2
:
iex(1)> rem(5, 2)
1
iex(2)> rem(5, 2) == 0
false
From the docs:
Computes the remainder of an integer division.
rem/2
uses truncated division, which means that the result will always have the sign of thedividend
.Raises an
ArithmeticError
exception if one of the arguments is not an integer, or when thedivisor
is 0.
The main differences compared to Ruby seem to be:
rem
only works with integers, but %
changes its behavior completely depending on the datatype.remainder
):Ruby:
irb(main):001:0> -5 / 2
=> -3
irb(main):002:0> -5 % 2
=> 1
irb(main):003:0> -5.remainder(2)
=> -1
Elixir:
iex(1)> -5 / 2
-2.5
iex(2)> rem(-5, 2)
-1
Elixir's rem
just uses Erlang's rem
, so this related Erlang question may also be useful.