Chapter 6 - Teach Yourself Scheme in Fixnum Days[Go to...

Info icon 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 6 Recursion A procedure body can contain calls to other procedures, not least itself: (define factorial (lambda (n) (if (= n 0) 1 (* n (factorial (- n 1)))))) This recursive procedure calculates the factorial of 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 letrec If we wanted the above procedures as local variables, we could try to use a let form: (1 of 5) [2/6/2008 11:40:01 AM]
Image of page 1

Info icon This preview has intentionally blurred sections. Sign up to view the full version.