elixir - 在 Elixir 中传递并使用命名函数?

标签 elixir

以下 Elixir 代码不正确,但传达了(我认为)所需的结果:

defmodule Question do
  def dbl(n), do: n * 2
  def trp(n), do: n * 3

  def consumer(xs, f) do
    Enum.filter(xs, f.(x) > 5)
  end
end

Question.consumer([1, 2, 3], dbl) # [3]
Question.consumer([1, 2, 3], trp) # [2, 3]

应该如何编写consumer方法来正确使用dbltrp?那么你会怎么调用它呢?

谢谢!

编辑:

请提出相关问题。您将如何在 Elixir 中编写和调用下面的 Scala 代码:

def dbl(n: Int): Int = n * 2
def trp(n: Int): Int = n * 3

def consume(xs: List[Int], f: (Int) => Int): List[Int] =
  xs.filter(x => f(x) > 5)

consume(List(1, 2, 3), dbl) # List(3)
consume(List(1, 2, 3), trp) # List(2, 3)

(谢谢)* 2

最佳答案

Elixir 中 Scala 的 x => f(x) > 5 的等价物是 fn x -> f.(x) > 5 end。这是你如何使用它:

defmodule Question do
  def dbl(n), do: n * 2
  def trp(n), do: n * 3

  def consumer(list, f) do
    Enum.filter(list, fn x -> f.(x) > 5 end)
  end
end

然后您可以使用以下方式调用它:

Question.consumer([1, 2, 3], &Question.dbl/1)   # => [3]
Question.consumer([1, 2, 3], &Question.trp/1)   # => [2, 3]
<小时/>

附加说明:

  • 您还可以使用简写 &(f.(&1) > 5) 代替完整函数
  • 注意 &/1 - 您需要传递对命名模块方法的完整引用。 See the Elixir guide on the Function captures
  • 另一方面,如果将 dbltrp 函数设为匿名,则可以直接将它们作为参数传递:

    dbl = fn n -> n * 2 end
    trp = fn n -> n * 3 end
    
    Question.consumer([1, 2, 3], dbl)   # => [3]
    Question.consumer([1, 2, 3], trp)   # => [2, 3]
    
  • 作为引用,请阅读:Why are there two kinds of functions in Elixir?

关于elixir - 在 Elixir 中传递并使用命名函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43132031/

相关文章:

elixir - 如何从表单上传大文件到 Phoenix ?

elixir - 关闭 : failed to start child: MyApp. Phoenix/Elixir 中的端点

elixir - 如何在 Elixir 中启动操作系统进程

file - 尝试使用Elixir在Docker内部打开文件时出错

iis - 在 Windows 上的 IIS 中运行 Phoenix 时内存泄漏/CPU 使用率持续居高不下

elixir - UndefinedFunctionError phoenix elixir 新项目

elixir - Controller 测试中的 Ecto.NoResultsError

pattern-matching - 有没有办法在 Elixir 的模式匹配中引用整个变量?

erlang - Elixir-Erlang : is there a "reasonable" limit of children handled by a supervisor?

elixir - String.replace 返回字符串的二进制表示