我如何在lua中编写总和(f,n)的高阶函数?
首先,我当然意识到,严格地说LUA不支持高级功能,而仅支持一流的功能。
但是,我想尝试实现某种功能,对于给定功能和数字n> = 0,返回总和0 + f 1 + ... + f n。我尝试这种尝试的方式,看起来像这样:
function sum(f,n)
if n < 1
then
return 0
else
return sum(f, n-1) + f(n)
end
end
我不确定当我尝试调用它时它是否真的做应该做的事情:
print(sum(函数(x)返回x*x end,2) ,3)
First of all, I am of course aware that strictly speaking Lua does not support higher order functions, but only first-class functions.
However, I would like to try to implement some kind of function which, for a given function and a number n >= 0, returns the sum 0 + f 1 + ... + f n. My way of attempting this, looks like this:
function sum(f,n)
if n < 1
then
return 0
else
return sum(f, n-1) + f(n)
end
end
I'm not sure though if it really does what it should do when I try to call it:
print(sum(function(x) return x*x end, 2),3)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是错误的。 LUA的功能是“一流” 允许高阶功能:您可以简单地将函数作为参数传递。
在lua repl,我得到了5 = 1^2 + 2^2的所需结果:
我看不到
,3
的目的(最终是>
的额外参数不过打印
)。更有效的实现将对 loop而不是递归使用
:
This is wrong. Lua's functions being "first-class" allows higher-order functions: You can simply pass functions as parameters.
Calling this in the Lua REPL, I get the desired result of 5 = 1^2 + 2^2:
I don't see the purpose of the
, 3
(which ends up as an extra argument toprint
) though.A more efficient implementation would use a
for
-loop instead of recursion: