【问题标题】:Is there a prefix/Polish notation for the equality operator in Elixir?Elixir 中的相等运算符是否有前缀/波兰符号?
【发布时间】:2016-05-06 12:47:18
【问题描述】:

我正在学习 Elixir,我决定给自己做的一个练习是尝试编写 Luhn algorithm 以在惯用的 Elixir 中进行信用卡验证。

我意识到 Elixir 中的 == 是一个内核函数,它显然是由编译器内联的。是否有某种实用功能可以让我做这样的事情?

...
|> == 0

而不必像我在这里所做的那样定义一个要输入的函数。

灵药

defmodule Luhn do
  def equalzero?(x) x == 0 end
  def validate(num) do
    digits = Integer.digits(num)
    len = length digits

    digits
    |> Stream.with_index
    |> Enum.reverse
    |> Enum.reduce(0, fn {digit, index}, acc ->
      if rem(len - index, 2) == 0 do
        acc + digit * 2 |> Integer.digits |> Enum.sum
      else
        acc + digit
      end
    end)
    |> rem(10)
    |> Luhn.equalzero?
  end
end

【问题讨论】:

    标签: elixir pointfree


    【解决方案1】:

    您可以通过引用它们的完整路径Kernel.== 来导入此类运算符(在Kernel 中定义):

    iex(1)> 0 |> Kernel.==(0)
    true
    iex(2)> 1 |> Kernel.==(0)
    false
    

    【讨论】:

      猜你喜欢
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      相关资源
      最近更新 更多