Can anybody suggest programming examples that illustrate recursive functions? There are the usual old horses such as Fibonacci series and Towers of Hanoi, but anything besides them would be fun.
相关问题
- PHP Recursively File Folder Scan Sorted by Modific
- recursion, Python, countup, countdown
- JavaScript fibonacci using recursion
- Find and print num of solutions to x1+x2+x3=num
- Understanding recursion in javascript and alternat
相关文章
- Recursively replace keys in an array
- Python: Maximum recursion depth exceeded when prin
- Is recursion good in SQL Server?
- How does this list comprehension over the inits of
- Find all subfolders of the Inbox folder using EWS
- What is the definition of “natural recursion”?
- Recursively decrement a list by 1
- When is tail recursion guaranteed in Rust?
In my opinion, recursion is good to know, but most solutions that could use recursion could also be done using iteration, and iteration is by far more efficient.
That said here is a recursive way to find a control in a nested tree (such as ASP.NET or Winforms):
The interpreter design pattern is a quite nice example because many people don't spot the recursion. The example code listed in the Wikipedia article illustrates well how this can be applied. However, a much more basic approach that still implements the interpreter pattern is a
ToString
function for nested lists:(Yes, I know it's not easy to spot the interpreter pattern in the above code if you expect a function called
Eval
… but really, the interpreter pattern doesn't tell us what the function is called or even what it does and the GoF book explicitly lists the above as an example of said pattern.)Here's a pragmatic example from the world of filesystems. This utility recursively counts files under a specified directory. (I don't remember why, but I actually had a need for something like this long ago...)
(Note that in Java a
File
instance can represent either a normal file or a directory. This utility excludes directories from the count.)A common real world example would be e.g.
FileUtils.deleteDirectory()
from the Commons IO library; see the API doc & source.This illustration is in English, rather than an actual programming language, but is useful for explaining the process in a non-technical way:
How about testing a string for being a palindrome?
Of course, you could do that with a loop more efficiently.
Once upon a time, and not that long ago, elementary school children learned recursion using Logo and Turtle Graphics. http://en.wikipedia.org/wiki/Turtle_graphics
Recursion is also great for solving puzzles by exhaustive trial. There is a kind of puzzle called a "fill in" (Google it) in which you get a grid like a crossword, and the words, but no clues, no numbered squares. I once wrote a program using recursion for a puzzle publisher to solve the puzzles in order be sure the known solution was unique.