Elixir 中的 operator 模块

Modulo operator in Elixir

如何在 Elixir 中使用模运算符?

例如在Ruby中你可以这样做:

5 % 2 == 0

它与 Ruby 的模运算符有何不同?

对于整数,使用 Kernel.rem/2:

iex(1)> rem(5, 2)
1
iex(2)> rem(5, 2) == 0
false

来自文档:

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.

与Ruby相比的主要区别似乎是:

  1. rem 仅适用于整数,但 % 完全根据数据类型改变其行为。
  2. Elixir 中负分红的符号为负(与Ruby的remainder相同):

Ruby:

irb(main):001:0> -5 / 2
=> -3
irb(main):002:0> -5 % 2
=> 1
irb(main):003:0> -5.remainder(2)
=> -1

长生不老药:

iex(1)> -5 / 2
-2.5
iex(2)> rem(-5, 2)
-1

Elixir 的 rem 只是使用了 Erlang 的 rem,所以 this related Erlang question 也可能有用。

使用rem/2见:https://hexdocs.pm/elixir/Kernel.html#rem/2 所以在 Elixir 中你的例子变成了:

rem(5,2) == 0

哪个returnsfalse

顺便说一句,您在 Elixir 中使用 % 编写的内容只是在行尾开始注释。

使用Integer.mod/2,见:https://hexdocs.pm/elixir/Integer.html#mod/2

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