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 iseven?
(lambda (n)
(if (= n 0) #t
(isodd? ( n 1)))))
(define isodd?
(lambda (n)
(if (= n 0) #f
(iseven? ( 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/tyschemeZH8.html (1 of 5) [2/6/2008 11:40:01 AM]
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentTeach Yourself Scheme in Fixnum Days
(let ((localeven? (lambda (n)
(if (= n 0) #t
(localodd? ( n 1)))))
(localodd? (lambda (n)
(if (= n 0) #f
(localeven? ( n 1))))))
(list (localeven? 23) (localodd? 23)))
This won't quite work, because the occurrences of
localeven?
and
localodd?
in the
initializations don't refer to the lexical variables themselves. Changing the
let
to a
let*
won't work
either, for while the
localeven?
inside
localodd?
's body refers to the correct procedure value,
This is the end of the preview. Sign up
to
access the rest of the document.
 Winter '08
 Fisler
 Recursion

Click to edit the document details