0

I have been making various functions that will compute the sigma in a range of very specific functions. I am now trying to write a sigma function that you would input a lambda or a function and it would then calculate the sum of its outputs within a range. I have the iteration code done fine but now need to figure out how to input a lambda and call it inside that function. here is my current code:

int sigma(int start, int end, ? function) {
    if (start == end) {
        return function(start);
    }
    else {
        return function(start) + sigma(start + 1, end, function);
    }
}

PS if anyone could help me make this not use recursion that would be amazing

user19273
  • 108
  • 9

2 Answers2

1

You can make this function into a function-template:

template<typename Fn>
int sigma(int start, int end, Fn function) {
 // ...
}

and then call it with a lambda:

auto lam = [](int) { return 42; };

std::cout << sigma(1, 5, lam);

To avoid the rescursion, the body could simply be:

int sum = 0;
for (int i = start; i <= end; ++i)
  sum += function(i);

return sum;
cigien
  • 57,834
  • 11
  • 73
  • 112
  • thank you. this method was exactly what I needed for this. how would I make the input function return either a float or an int? – user19273 Apr 26 '20 at 17:51
  • If you notice, nowhere is it specified what the function must return. So you could do that. However, withing `sigma`, you have to choose (at compile time), what type you want the input function to return. – cigien Apr 26 '20 at 17:54
0

You need the type for your parameter. So ask yourself what is this parameter supposed to be? Based upon your definition of sigma(), you appear to be expecting a function-like object that is invoked with an int parameter and returns an int. That is, a std::function<int(int)>. Your function's declaration might end up looking like the following.

int sigma(int start, int end, std::function<int(int)> & function);

If you want to handle functions with other signatures, then a function template might be more appropriate. See std::function vs template for a discussion.

JaMiT
  • 14,422
  • 4
  • 15
  • 31