BadFunctionError 需要一个函数
BadFunctionError expected a function
我正在尝试实现一个以列表和函数作为参数的函数,然后将该函数应用于列表的每个元素,然后对结果求和,但每次我 运行 iex 中的程序,我得到错误 - ** (BadFunctionError) expected a function, got: 1. 我似乎无法弄清楚问题是什么。我是 Elixir 和函数式编程的新手。
defmodule MyList do
def mapsum([], _func) do
0
end
def mapsum([head | tail], func) do
func.(head) + mapsum(tail, func.(head))
end
end
我明白了,问题出在 mapsum 函数体内的 func.(head)
参数。
defmodule MyList do
def mapsum([], _func) do
0
end
def mapsum([head | tail], func) do
func.(head) + mapsum(tail, func)
end
end
请注意,Mohamed 的回答虽然有些正确,但并未 Tail Call 优化,因此可能会炸毁堆栈。
这是 TCO 版本。
defmodule MyListTCO do
def mapsum(list, func, acc \ 0)
def mapsum([], _, acc), do: acc
def mapsum([head | tail], func, acc),
do: mapsum(tail, func, acc + func.(head))
end
虽然原始版本 可能会在大量输入时崩溃 ,但由于堆栈耗尽,这个版本会很高兴 return。
幸运的是,erlang 编译器足够聪明,可以优化上面的调用以降低 TCO,因为它可以做到。但最好不要依赖编译器并牢记这一点。
我正在尝试实现一个以列表和函数作为参数的函数,然后将该函数应用于列表的每个元素,然后对结果求和,但每次我 运行 iex 中的程序,我得到错误 - ** (BadFunctionError) expected a function, got: 1. 我似乎无法弄清楚问题是什么。我是 Elixir 和函数式编程的新手。
defmodule MyList do
def mapsum([], _func) do
0
end
def mapsum([head | tail], func) do
func.(head) + mapsum(tail, func.(head))
end
end
我明白了,问题出在 mapsum 函数体内的 func.(head)
参数。
defmodule MyList do
def mapsum([], _func) do
0
end
def mapsum([head | tail], func) do
func.(head) + mapsum(tail, func)
end
end
请注意,Mohamed 的回答虽然有些正确,但并未 Tail Call 优化,因此可能会炸毁堆栈。
这是 TCO 版本。
defmodule MyListTCO do
def mapsum(list, func, acc \ 0)
def mapsum([], _, acc), do: acc
def mapsum([head | tail], func, acc),
do: mapsum(tail, func, acc + func.(head))
end
虽然原始版本 可能会在大量输入时崩溃 ,但由于堆栈耗尽,这个版本会很高兴 return。
幸运的是,erlang 编译器足够聪明,可以优化上面的调用以降低 TCO,因为它可以做到。但最好不要依赖编译器并牢记这一点。