Chapter 6

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

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
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: file:///C|/Documents%20and%20Settings/Linda%20Grauer. ..otes/Teach%20Yourself%20Scheme/t-y-scheme-Z-H-8.html (1 of 5) [2/6/2008 11:40:01 AM]
Background image of page 1

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

View Full DocumentRight Arrow Icon
Teach Yourself Scheme in Fixnum Days (let ((local-even? (lambda (n) (if (= n 0) #t (local-odd? (- n 1))))) (local-odd? (lambda (n) (if (= n 0) #f (local-even? (- n 1)))))) (list (local-even? 23) (local-odd? 23))) This won't quite work, because the occurrences of local-even? and local-odd? in the initializations don't refer to the lexical variables themselves. Changing the let to a let* won't work either, for while the local-even? inside local-odd? 's body refers to the correct procedure value,
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 5

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

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online