Why use recursive functions




















Active Oldest Votes. To see why, walk through the steps that the above languages use to call a function: space is carved out on the stack for the function's arguments and local variables the function's arguments are copied into this new space control jumps to the function the function's code runs the function's result is copied into a return value the stack is rewound to its previous position control jumps back to where the function was called Doing all of these steps takes time, usually a little bit more than it takes to iterate through a loop.

Good to see an explanation of the inherent overhead of recursion. I touched on that in my answer as well. But to me, the big strength with recursion is what you can do with the call stack.

See my answer for an example. Very disappointed to find the top answer to a question titled "What is recursion and when should I use it? You're probably right Dukeling. For context, when I wrote this answer there were many great explanations of recursion already written and I wrote this intending to be an adjunct to that info, not the top answer. In practice when I need to walk a tree or handle any other nested data structure I usually turn to recursion and I've yet to hit a stack overflow of my own making in the wild.

Add a comment. Simple english example of recursion. A child couldn't sleep, so her mother told her a story about a little frog, who couldn't sleep, so the frog's mother told her a story about a little bear, who couldn't sleep, so the bear's mother told her a story about a little weasel There is a similar story like this for little kids who won't fall asleep in Chinese folk tales, I just remembered that one, and it reminds me how real world recursion works.

Christopher: This is a nice, simple example of recursion. Specifically this is an example of tail recursion. However, as Andreas stated, it can easily be rewritten more efficiently with a for loop. As I explain in my answer, there are better uses for recursion. No, it's only there for clarity. Were it written to pass the length-so-far along, only then could we forget the caller existed. Add new Point3D x - len, y - len, -len ; mesh. Conclusion In practical terms, recursion makes the most sense whenever you need iterative branching.

Good explanation, but I think it's important to note that this is simply tail recursion and offers no advantage over the iterative solution. It's roughly the same amount of code, and will run slower due to the function call overhead. SteveWortham: This isn't tail recursion. In the recursive step, the result of FactRec has to be multiplied by n before returning. Quoted from the exact article you linked: "A divide and conquer algorithm works by recursively breaking down a problem into two or more sub-problems of the same or related type," — Amber.

I don't think that is a great explanation, since recursion strictly speaking does not have to solve problem at all. You could just call yourself And overflow. Hope you don't mind. Consider an old, well known problem : In mathematics, the greatest common divisor gcd … of two or more non-zero integers, is the largest positive integer that divides the numbers without a remainder. The definition of gcd is surprisingly simple: where mod is the modulo operator that is, the remainder after integer division.

Let's compute gcd 10, 8 as an example. Each step is equal to the one just before it: gcd 10, 8 gcd 10, 10 mod 8 gcd 8, 2 gcd 8, 8 mod 2 gcd 2, 0 2 In the first step, 8 does not equal zero, so the second part of the definition applies. A function that calls itself When a function can be easily decomposed into a simple operation plus the same function on some smaller portion of the problem.

I should say, rather, that this makes it a good candidate for recursion. They do! Louis Brandy. If you get into an infinite recursive loop, you will get a Stack Overflow exception : I can't think of a reason why people shouldn't use it, when appropriate. Recursion is an expression directly or indirectly referencing itself. People avoid recursion for a number of reasons: Most people myself included cut their programming teeth on procedural or object-oriented programming as opposed to functional programming.

Joey deVilla. Generally speaking, recursive procedures have two parts: 1 The recursive part, which defines some procedure in terms of new inputs combined with what you've "already done" via the same procedure. Hope this helps Gregory Brown. Don't use recursion for factorials or Fibonacci numbers One problem with computer-science textbooks is that they present silly examples of recursion.

Most of the reason why factorials or fibonacci sequences are used as examples is because they're common items that are defined in a recursive manner, and thus they lend themselves naturally to examples of recursion to calculate them - even if that's not actually the best method from a CS standpoint.

When to use recursion Q: Does using recursion usually make your code faster? A: No. Q: Does using recursion usually use less memory? Q: Then why use recursion? A: It sometimes makes your code much simpler! What about reducing complexity when divide and conquer concerning perfs?

First, we need two rules: if the set is empty, the count of items in the set is zero duh! Suppose you have a set like this: [x x x]. Now the set is [], which matches rule 1: the count is zero! This is usually some variation of "if you are out of data to process, your answer is X" the recursive rule, which states what happens if you still have data.

This is usually some kind of rule that says "do something to make your data set smaller, and reapply your rules to the smaller data set. Dave Markle. Peter Burns. In plain English: Assume you can do 3 things: Take one apple Write down tally marks Count tally marks You have a lot of apples in front of you on a table and you want to know how many apples there are. I hope this is the "plain english" answer you are looking for!

Bastiaan Linders. Wait, i have a lot of tally marks in front of me on a table, and now i want to know how many tally marks there are. Can i somehow use the apples for this?

If you take an apple from the ground when you've put them there during the process and place it on the table each time you scratch one tally mark of the list until there are no tally marks left, i'm pretty sure you end up with an amount of apples on the table equal to the number of tally marks you had. Now just count those apples for instant success! You want to use it anytime you have a tree structure. It is very useful in reading XML. Nick Berardi. Example Suppose your desk is covered with a disorganized mess of papers.

Divide: Spread all the sheets out, so you have just one sheet in each "stack". Conquer: Go around, putting each sheet on top of one other sheet. You now have stacks of 2. Go around, putting each 2-stack on top of another 2-stack. You now have stacks of 4. Go around, putting each 4-stack on top of another 4-stack. You now have stacks of 8. You now have one huge stack of sheets!

Andres Jaan Tack. That's fine. I'm not trying to capture [the world of recursion][1] in a sentence, here. I want an intuitive explanation. Luka Ramishvili. In plain English, recursion means to repeat someting again and again. In programming one example is of calling the function within itself. In plain English, to repeat something again and again is called iteration. Syed Tayyab Ali. The Overflow Blog. Does ES6 make JavaScript frameworks obsolete? Assuming the code is completed with one of the base cases identified in the previous problem, what does stringValue , 16 do?

Factorial is easy to define in terms of smaller subproblems. Having a recursive problem like this is one cue that you should pull a recursive solution out of your toolbox. Another cue is when the data you are operating on is inherently recursive in structure. A filesystem consists of named files. Some files are folders , which can contain other files. So a filesystem is recursive: folders contain other folders which contain other folders, until finally at the bottom of the recursion are plain non-folder files.

The Java library represents the file system using java. This is a recursive data type, in the sense that f. Recent versions of Java have added a new API, java. Files and java. Path , which offer a cleaner separation between the filesystem and the pathnames used to name files in it. But the data structure is still fundamentally recursive.

Recursion — a method calling itself — is a special case of a general phenomenon in programming called reentrancy. Reentrant code can be safely re-entered, meaning that it can be called again even while a call to it is underway. Direct recursion is one way that reentrancy can happen. Mutual recursion between two or more functions is another way this can happen — A calls B, which calls A again.

Direct mutual recursion is virtually always intentional and designed by the programmer. But unexpected mutual recursion can lead to bugs. When we talk about concurrency later in the course, reentrancy will come up again, since in a concurrent program, a method may be called at the same time by different parts of the program that are running concurrently. Reentrant code is safer from bugs and can be used in more situations, like concurrency, callbacks, or mutual recursion. Another reason to use recursion is to take more advantage of immutability.

In an ideal recursive implementation, all variables are final, all data is immutable, and the recursive methods are all pure functions in the sense that they do not mutate anything. The behavior of a method can be understood simply as a relationship between its parameters and its return value, with no side effects on any other part of the program. This kind of paradigm is called functional programming , and it is far easier to reason about than imperative programming with loops and variables.

In iterative implementations, by contrast, you inevitably have non-final variables or mutable objects that are modified during the course of the iteration. One downside of recursion is that it may take more space than an iterative solution. Building up a stack of recursive calls consumes memory temporarily, and the stack is limited in size, which may become a limit on the size of the problem that your recursive implementation can solve.

On the bright side, what would be an infinite loop in an iterative implementation usually becomes a StackOverflowError in a recursive implementation. A buggy recursive program fails faster.

For subsequences "" , how deep does its recursive call stack get? How many recursive calls to subsequences can be active at the same time?

Safe from bugs. Recursive code is simpler and often uses immutable variables and immutable objects. Easy to understand. Recursive implementations for naturally recursive problems and recursive data are often shorter and easier to understand than iterative solutions. Ready for change. Recursive code is also naturally reentrant, which makes it safer from bugs and ready to use in more situations.

Software in 6. Change Language. Related Articles. Table of Contents. Save Article. Improve Article. Like Article. Assuming n-th disk is. Base case termination condition.

Move first n-1 disks. Move the remaining. Move the n-1 disks from. Increase call depth. Decrease call depth. This code is contributed by Pratham Next Recursion. Article Contributed By :. Easy Normal Medium Hard Expert. Writing code in comment? Please use ide. Load Comments. What's New.



0コメント

  • 1000 / 1000