Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How would I write an higher-order function of sum(f,n) in Lua?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

print(sum(function(x) return x*x end, 2),3)

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading