Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 11. AppleScript Subroutines > Reusing Subroutines - Pg. 219

Chapter 11: AppleScript Subroutines In order to create a subroutine that calculates the factorial of a positive integer, you need the subrou- tine to call itself recursively until the sequence is done. So here is the code that does exactly that: on factorial(x) if x > 0 then return x * (factorial(x - 1)) else return 1 end if end factorial To run the code, you give the subroutine a positive integer. If that integer is greater than 0, it returns a value of that integer multiplied by the result of the factorial of the integer minus 1, recur- sively until the integer is no longer zero. Because it's recursive, you get a return value of the com- bined result. Figure 11.3 shows the results of factorial(10) . As you can see, it's not hard to generate some pretty big numbers with a simple factorial subroutine. FIGURE 11.3 Running factorial(10)