我如何在lua中编写总和(f,n)的高阶函数?

发布于 2025-01-24 21:46:28 字数 338 浏览 1 评论 0原文

首先,我当然意识到,严格地说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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忱杏 2025-01-31 21:46:28

首先,我当然知道严格地说lua不支持高级功能,而只支持一流的功能。

这是错误的。 LUA的功能是“一流” 允许高阶功能:您可以简单地将函数作为参数传递。

我不确定当我尝试调用它时它是否真的做应该做的:print(sum(function(x)return x*x end,2),3),3)

在lua repl,我得到了5 = 1^2 + 2^2的所需结果:

$ lua
Lua 5.3.4  Copyright (C) 1994-2017 Lua.org, PUC-Rio
> function sum(f,n)
>>     if n < 1 
>> then 
>>     return 0
>> else
>>     return sum(f, n-1) + f(n)
>>     end
>> end
> 
> print(sum(function(x) return x*x end, 2),3)
5   3

我看不到,3的目的(最终是> 的额外参数不过打印)。

更有效的实现将对 loop而不是递归使用

function sum(f, n)
    local sum = 0
    for i = 1, n do
        sum = sum + f(i)
    end
    return sum
end

First of all, I am of course aware that strictly speaking Lua does not support higher order functions, but only first-class functions.

This is wrong. Lua's functions being "first-class" allows higher-order functions: You can simply pass functions as parameters.

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)

Calling this in the Lua REPL, I get the desired result of 5 = 1^2 + 2^2:

$ lua
Lua 5.3.4  Copyright (C) 1994-2017 Lua.org, PUC-Rio
> function sum(f,n)
>>     if n < 1 
>> then 
>>     return 0
>> else
>>     return sum(f, n-1) + f(n)
>>     end
>> end
> 
> print(sum(function(x) return x*x end, 2),3)
5   3

I don't see the purpose of the , 3 (which ends up as an extra argument to print) though.

A more efficient implementation would use a for-loop instead of recursion:

function sum(f, n)
    local sum = 0
    for i = 1, n do
        sum = sum + f(i)
    end
    return sum
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文