I’ve been doing problems on recursion in my Data Structures & Algorithms class and for some tail-recursive functions I couldn’t think of doing anything but having the main function call a helper function and the helper function being the tail recursive part since I had to pass different parameters than the original function.
While this is technically tail-recursive the original function is the one that ends up handling the base cases and in the main case passes the additional parameters to the actual tail recursive function.
Obviously this sort of defeats the idea of recursion, especially in a class setting for homework, exams and such.
That’s why today I thought, instead of making a helper function, couldn’t I make an overloaded version of the function that accepts those additional parameters and continues the work? It would technically be recursive since all the calls in the function are to itself, albeit with more parameters than the initial call.
Here’s a rough example:
int fibonacci(int n) {
if (n == 1)
return 1;
else
return fibonacci(n, 2, 1, 2);
}
int fibonacci(int n, int f1, int f2, int c) {
if (c == n)
return f1;
else
return fibonacci(n, f1 + f2, f1, c + 1);
}
Is it still recursion in the definition sense? Would it work? Would the compilers that do recursion optimization (don’t know how it works exactly, but know it exists) apply that to this?
I assume that it’s still recursion since it’s technically calling itself still and I would think it would optimize, just ignoring the initial call. But that’s why I’m asking, to see if I’m right or not.
Yes, I would still call this “recursion.” The one-argument overload of
fibonacciis not recursive, but the 4-argument overload is recursive without a doubt.That said: don’t fool yourself into thinking that the
fibonaccifunction overall is recursive. The one-argument overload never calls itself. In Java-like languages, where a function/method is uniquely defined by its signature, you still have two distinct functions.