Every textbook I’ve ever seen on recursive functions uses the factorials
as an example, which is helpful but not totally illuminating.
For programming purposes, can a recursive function take a function as its base
case, can it include other function calls within its body, or can it execute
differently at different levels of recursion?
And if it does these any of these things, is it still a ‘recursive function’
or is it now something else?
This is a fairly straightforward example of a recursive function that simply outputs all of the values in a collection, an array represented as a stack, to the browser console as it pops them off of the stack using the .pop() method.
The totalSize value doesn’t change throughout the entire call stack so that it can be used to measure the halfway point by dividing the current stack size by the original size.
To answer the question of can it behave differently at different levels in the recursion, the answer is yes:
Additionally, you also asked if it were possible to call other functions, this is also possible. In the example below, a function is used to return the result of the base case,
and a function is used to abstract the halfway point behavior:
While these particular examples don’t solve any real-world problem, it demonstrates how the concept of calling a function inside another function could expand to handle other use-cases. The examples in your textbook are simply designed to teach you the basics of recursion and help arm you with the tools necessary to take on more complex, real-world problems in the future.
Since this functional language is JavaScript, the barriers to running them are low. You can try these examples by running the code in the Chrome Developer Console, or you could run them in a small test HTML file. Good luck!