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)
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