8.7. Recursive Handlers

Not only can a handler call other handlers, but it can also call itself! When a handler does that, it is called a recursive handler. Recursion is often a suitable choice for problems that can be solved by applying the same solution to subsets of the problem. Examples might be in the evaluation of parenthesized expressions, processing the elements of a list, or enumerating the contents of a folder, which itself might contain subfolders.

Perhaps the most commonly used illustration of recursion is in the calculation of factorials. The factorial of a positive integer n, written n!, is the product of the integers from 1 through n, inclusive. So the factorial of 5, or 5!, is calculated like this:

5! = 5 { 4 { 3 { 2 { 1 = 120

And the calculation of 6! is done like this:

6! = 6 { 5 { 4 { 3 { 2 { 1 = 720

If you compare the calculation of 6! to that of 5!, you may notice that 6! is equal to 6 ( 5!. In general, the factorial of any positive integer n can be expressed as the product of n and the factorial of n − 1:

n! = n { (n − 1)!

Defining the factorial of n! like this is a recursive definition because the calculation of the factorial is based on the calculation of another factorial. The following Try It Out gives you some practice with writing a recursive handler.

8.7.1.

8.7.1.1. Try It Out: Recursive Factorial Handler

In the following program, you write a recursive handler called factorial that calculates the factorial of an integer given as its argument.

Get Beginning AppleScript® 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.