Recursive Functions
A
recursive
function is a function that calls itself (by using its own name
within its function body). Here’s a simple example that shows
the principle of recursion. But because the code tells the
trouble( )
function to execute repeatedly (like
an image reflected infinitely in two opposing mirrors), Flash will
quickly run out of memory, causing an error:
function trouble( ) { trouble( ); }
Practical recursive functions call themselves only while a given condition is met (thus preventing infinite recursion). Example 9.4 used recursion to count from a specified number down to 1, but obviously that can be accomplished without recursion.
One classic use of recursion is to calculate the mathematical factorial of a number. The factorial of 3 (written as 3! in mathematical nomenclature) is 3*2*1=6. The factorial of 5 is 5*4*3*2*1=120. Example 9.8 shows a factorial function that uses recursion.
Example 9-8. Calculating Factorials Using Recursion
function factorial(x) { if (x < 0) { return undefined; // Error condition } else if (x <= 1) { return 1; } else { return x * factorial(x-1); } } trace (factorial(3)); // Displays: 6 trace (factorial(5)); // Displays: 120
As usual, there is more than one way to skin a proverbial cat. Using a loop, we can also calculate a factorial without recursion, as shown in Example 9.9.
Example 9-9. Calculating Factorials Without Recursion
function factorial(x) { if (x < 0) { return undefined; // Error condition } else { var result = 1; for (var ...
Get ActionScript: The Definitive Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.