Search code examples
c++c++11recursionlambdastd-function

How to make a recursive lambda function that takes 2 arguments not 1?


I already know how to make a recursive lambda function that take one argument like calculating factorial of a number, but I try to make a recursive power function using lambda (as a practice), but taking 2 arguments in the function caused errors

this the code :

std::function <int(int)> power = [&](int a, int n)
{
    return (n<=1) ? a : a*power(a, n-1);
};

this line return (n<=1) ? a : a*power(a, n-1); gives these errors :

error:   no match for call to '(std::function<int(int)>) (int&, int)'
note:   candidate: _Res std::function<_Res(_ArgTypes ...)>::operator()(_ArgTypes ...) const [with _Res = int; _ArgTypes = {int}]
note:   candidate expects 1 argument, 2 provided

Solution

  • You'll have to use

    std::function <int(int, int)> power = [&](int a, int n) { ... }
    

    for the function to work with two arguments.

    Suggestions for improment:

    Make sure you deal with n = 0 correctly.

    Use of

    return (n <= 1) ? a : a*power(a, n-1);
    

    is not right. You will get back a when the function is called with n = 0.

    Use

    return (n == 0) ? 1 : a*power(a, n-1);
    

    Use unsigned int for n.

    std::function <int(int, unsigned int)> power = [&](int a, unsigned int n) { ... }
    

    Then, you won't have to worry about the function getting called with negative values for n.


    Complete function

    std::function <int(int, unsigned int)> power = [&](int a, unsigned int n)
    {
        return (n == 0) ? 1 : a*power(a, n-1);
    };