【发布时间】:2016-12-03 09:35:11
【问题描述】:
可能是一个非常基本的 Elixir 问题,
我想将偶数从 1 加到 10 并输出到 IO.puts
首先我尝试这样做:
1..10
|> Enum.filter(fn (x) -> rem(x, 2) == 0 end)
|> Enum.sum
|> IO.puts
按预期工作。
然后我尝试在模块中定义该函数:
defmodule Test do
def is_even(x) do
rem(x, 2) == 0
end
end
1..10
|> Enum.filter(Test.is_even)
|> Enum.sum
|> IO.puts
但这给了我以下编译错误:
** (UndefinedFunctionError) undefined function: Test.is_even/0
Test.is_even()
tmp/src.exs:8: (file)
(elixir) src/elixir_lexical.erl:17: :elixir_lexical.run/3
(elixir) lib/code.ex:316: Code.require_file/2
为什么它应该(按我的意图)寻找 is_even/1 却寻找 is_even/0?
我不明白为什么会这样,尤其是这样做之后:
defmodule Test do
def hello(x) do
IO.puts(x)
end
end
Test.hello("Hello World!")
工作得很好。
我也刚刚发现这是可行的:
defmodule Test do
def is_even() do
fn (x) -> rem(x, 2) == 0 end
end
end
1..10
|> Enum.filter(Test.is_even)
|> Enum.sum
|> IO.puts
为什么它使用函数的返回作为函数使用而不是使用函数本身?
有没有办法让这个工作而不必在函数内部返回匿名函数?
【问题讨论】:
标签: elixir