I was wondering if something like this could be used in code.
If I had a block of code I wanted to execute that was the same at many parts of the program
and it used this version of the while loop, would this work?
(I am aware that I could use a while loop, I just thought this would be an interesting idea to explore)
NSMutableArray *objects;
-(void) RemoveObjectLoop
{
[self RemoveObjectAtZero];
}
-(void) RemoveObjectAtZero
{
if([objects count] > 0)
{
[objects removeObjectAtIndex:0];
[self RemoveObjectLoop];
}
}
Instead of writing out a while loop multiple times just do [self RemoveObjectLoop].
Could this work for a project?
Is there any instance where you wouldn’t want to use this?
Edit: I know this example is bad, I just couldn’t think of anything else.
If you could, please include an example in your answer. Thanks!
In recursion you normally wouldn’t have a circular function call like that. The function would just call itself while working toward a conclusion. So your example would become:
Some languages (like Logo) will automatically optimize tail recursion (where the recursive call is the last line of the function). I’ve never heard of Objective-C doing that and I’d be surprised if it did.
Usually (your question being a case in point as you’ve noted) recursion examples are contrived and would be better solved non-recursively. Here are some real-world examples of recursion.