Reputation: 14220
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?
Upvotes: 23
Views: 31743
Reputation: 23139
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.
Upvotes: 30
Reputation: 3661
Use Integer.mod/2
, see: https://hexdocs.pm/elixir/Integer.html#mod/2
iex>Integer.mod(-5, 2)
1
Upvotes: 10
Reputation: 3069
Use rem/2
see: https://hexdocs.pm/elixir/Kernel.html#rem/2
So in Elixir your example becomes:
rem(5,2) == 0
which returns false
BTW what you wrote using %
in Elixir simply starts a comment to the end of the line.
Upvotes: 6