0

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!

Telinir
  • 139
  • 1
  • 11

2 Answers2

3

This is called recursion. In languages that don't optimize for it, it is only usable for moderately sized collections because eventually you will run out of stack space to hold the frames needed for the functions. It's also somewhat slower than a normal loop (again, unless the compiler optimizes for it).

For some algorithms, it is a good fit. For example, depth-first searches are naturally implemented as recursive functions. I don't think this is one of those cases, though.

Chuck
  • 234,037
  • 30
  • 302
  • 389
1

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:

-(void) RemoveAll
{
    if([objects count] > 0)
    {
        [objects removeObjectAtIndex:0];
        [self RemoveAll];
    }
}

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.

Community
  • 1
  • 1
SSteve
  • 10,550
  • 5
  • 46
  • 72
  • Thanks for explaining it and providing an example! – Telinir Dec 03 '11 at 18:04
  • 1
    You're welcome. Depending on the type of programming you're doing you can go years without ever needing to use recursion but every now and then it is an almost magically elegant way to solve a problem so it's a good thing to have in your tool chest. – SSteve Dec 03 '11 at 19:52