0

I have written a function that works really well for what it is intended, but I just realized that it will need to make calls to itself, and wondered if that is able to be done (first), whether is is a smart thing to do (second), and are there any potential pitfalls (third).

It is a function that places new members positions and then checks to see if the placement caused another member to cycle. When it does cause a cycle, then it automatically creates additional (re-entry) positions, but then it has to check to see if another cycle has been created, which is likely...

So I would need to call the function from within itself, and this could happen multiple times, as the membership position base expands, because the number of consecutive cycles doubles with each successive level.

I hope this makes sense, and it is probably unnecessary to explain all of this to just get the simple question answered, that is if it is in fact a simple question...

So, any help, suggestions, discouragements, etc.?

Looking forward to a speedy response from someone with the right answer, because I am at a point of needing to make this work, now...

thanks in advance

Douglas:?:

3
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by showman13
1

1. Yes.
2. Maybe, depending on your implementation.
3. When not handled correctly, or a lot of deep calls, it can cause a stack overflow.

If you are absolutely sure a recursive function is the only way, just do it. Remember that there is most likely a non-recursive solution too.

Votes + Comments
Perfect answer
0

It's called an iterator. You can do it, but there has to be an escape mechanism - there must be a point where the iterator breaks, otherwise you'll get an infinite loop. Smart? Depends on the implementation and how robust the system is. php has a number of in-built iterators (see SPL). You also need to consider memory and storage issues. Massive loops could cause timeout problems, etc.

Anyhow, I'm no expert. Just a few things that hit me over the years.

//EDIT
Sorry Pritaeas - simultaneous post - "recursive" was the term I was looking for.

Edited by diafol: n/a

1

Thank you for your responses.

What I ended up doing is taking out the chunk of the function that would have required it to be recursive, and put it into the calling script. Then just set up a while loop and gathered the additional positions that needed to be placed into an array, sort of like a stack, by pushing them onto the array, and continuing to walk through the array until all elements were gone.

That way I could call the function on each insertion, and if it created a cycle, it would just push more elements onto the array.. Kewl resolution, if I do say so myself...

Thanks again for the feedback.

Douglas

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.