
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Nested Functions
|
205
Which approach is better—recursive or nonrecursive—depends on the problem.
Some problems are solved more easily using recursion, but recursion can be slower
than nonrecursive solutions. Recursion is best used when you don’t know how
deeply a data structure may be nested. For example, suppose you wanted to list all
the files within a subdirectory, including listing all files within any nested subdirec-
tory, ad infinitum. It would be inconvenient to write a general solution that worked
for any number of subdirectories without resorting to recursion. A recursive solution
might look like this in pseudocode:
function listFiles (directoryName) {
do (check the next item in directoryName) {
if (this item is a subDirectory itself) {
// Recursively call this function with the new subdirectory
listFiles(subDirectoryName);
} else {
// Display the name of this file
trace(filename);
}
} while(there are still items to check);
}
When we consider the XML object the Language Reference, we’ll use recursion to list
all the elements in an XML document.
Nested Functions
In ActionScript, functions can be declared within functions. Example 9-10 creates a
function, showFullName( ), with two nested functions, showFirstName( ) and
showLastName( ).
Inside showFullName( ), the nested functions ...