What is a Recursive Function?
It's a function that calls itself.
Why would you want a function to call itself?
Aside from a great way to lock up a computer, recursive functions are useful as a way to iterate through a dataset and create a superstructure based on that data set.
This still isn't interesting. How about an example
My first actually useful implementation was more than a decade ago. I used recursion to dynamically generate a tree structure based on database values. Unfortunately, it wasn't very efficient as it generated an unknown amount of database queries. Still it got the job done and it's a decent example of one of the caveats involved with recursing functions - they can cause a performance hit if you don't make an effort to reign them in.
Let's say you have a data object describing people:
Person => Name: Ed Phone Number: 867-5309 Eyes: Brown Hair: Blue Siblings: [*Mary, *Jim, *Henry]
Now let's say you want to serialize your data object. You could write a simple function to iterate through the properties:
Serialize = function(object) {
foreach (property in object){
if(property.type = regular property){
text += property.name + " = " + property.value
} else if (property.type = nested property) {
text += property.name + " = " + Serialize (property.value);
}
return text;
}
It saves you the trouble of having to write very specific functions based on your defined data structure and it has the side benefit of being a reusable code snippet that you can use in other projects.
Booring
Still bored. Want your 2 minutes back? Maybe this will make up for it.
Join The Recursive Functions Discussion
