This preview shows pages 1–3. Sign up to view the full content.
Teach Yourself Scheme in Fixnum Days [Go to first, previous, next page; contents; index]Chapter 6RecursionA procedure body can contain calls to other procedures, not least itself:(define factorial(lambda (n)(if (= n 0) 1(* n (factorial (- n 1))))))This recursiveprocedure calculates the factorialof a number. If the number is 0, the answer is 1. For any other number n, the procedure uses itself to calculate the factorial of n - 1, multiplies that subresult by n, and returns the product.Mutually recursive procedures are also possible. The following predicates for evenness and oddness use each other:(define is-even?(lambda (n)(if (= n 0) #t(is-odd? (- n 1)))))(define is-odd?(lambda (n)(if (= n 0) #f(is-even? (- n 1)))))These definitions are offered here only as simple illustrations of mutual recursion. Scheme already provides the primitive predicates even?and odd?.6.1 letrecIf we wanted the above procedures as local variables, we could try to use a letform: (1 of 5) [2/6/2008 11:40:01 AM]
This preview
has intentionally blurred sections.
Sign up to view the full version.