dan-klasson
dan-klasson

Reputation: 14220

Modulo operator in Elixir

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

Answers (3)

Adam Millerchip
Adam Millerchip

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 the dividend.

Raises an ArithmeticError exception if one of the arguments is not an integer, or when the divisor is 0.

The main differences compared to Ruby seem to be:

  1. rem only works with integers, but % changes its behavior completely depending on the datatype.
  2. The sign is negative for negative dividends in Elixir (the same as Ruby's 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

Sam Houston
Sam Houston

Reputation: 3661

Use Integer.mod/2, see: https://hexdocs.pm/elixir/Integer.html#mod/2

iex>Integer.mod(-5, 2)
1

Upvotes: 10

GavinBrelstaff
GavinBrelstaff

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

Related Questions