[英]How do I call an anonymous function inside Enum.map
I am learning Elixir and I am working on Project Euler to try to strengthen my skills in Elixir. 我正在学习Elixir,我正在研究Project Euler,试图加强我在Elixir的技能。 Right now I have this code
现在我有这个代码
fib = fn
a,b,0 -> a
a,b,n -> fib.(b, a+b, n-1)
end
IO.puts Enum.sum(Enum.filter(Enum.map(1..50, fn n -> fib.(0,1,n) end), even and fn(x) -> x < 4000000 end))
But when I run this code I get: 但是,当我运行此代码时,我得到:
undefined function fib/0
(elixir) src/elixir_fn.erl:33: anonymous fn/3 in :elixir_fn.expand/3
(stdlib) lists.erl:1238: :lists.map/2
(stdlib) lists.erl:1238: :lists.map/2
(elixir) src/elixir_fn.erl:36: :elixir_fn.expand/3
How do I fix this? 我该如何解决?
Elixir does not allow defining anonymous recursive functions at this moment. Elixir目前不允许定义匿名递归函数。 You have 2 options: define a normal function using
def
inside any module, or use the following trick (hack?) to make kind of anonymous recursive functions: 你有两个选择:在任何模块中使用
def
定义一个普通函数,或者使用下面的技巧(hack?)来制作一种匿名递归函数:
fib = fn
fib, a, b, 0 -> a
fib, a, b, n -> fib.(fib, b, a+b, n-1)
end
IO.puts Enum.sum(Enum.filter(Enum.map(1..50, fn n -> fib.(fib, 0, 1, n) end), fn(x) -> rem(x, 2) == 0 && x < 4000000 end))
I would recommend defining this function in a module instead of using this hack: 我建议在模块中定义此函数,而不是使用此hack:
defmodule Fib do
def fib(a, _b, 0), do: a
def fib(a, b, n), do: fib(b, a + b, n - 1)
end
IO.puts Enum.sum(Enum.filter(Enum.map(1..50, fn n -> Fib.fib(0, 1, n) end), fn(x) -> rem(x, 2) == 0 && x < 4000000 end))
Note: there was also a syntax error in the second argument to Enum.filter/2
which I've fixed (hopefully correctly). 注意:
Enum.filter/2
的第二个参数中也存在语法错误,我已经修复了(希望是正确的)。
Tip: please read about the pipe operator to make the IO.puts
code more idiomatic: http://elixir-lang.org/getting-started/enumerables-and-streams.html#the-pipe-operator 提示:请阅读有关管道运算符的信息,以使
IO.puts
代码更具惯用性: http : IO.puts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.