The Scheme definition
(define sum-iter (lambda(n acc i) (if (> i n) acc (sum-iter n (+ acc i) (+ i 1)))))
solves the problem of summing the integers 1 to 5 when applied to the arguments 5 0 1. We can create a new definition
sum1
which solves the problem of summing the integers 1 to k,
given the size of the problem k, with the definition
(define sum1 (lambda(k) (sum-iter k 0 1)))
Analysis of
sum1
involves analyzing sum-iter
since
sum1
makes a single call to sum-iter
. The definition
of sum-iter
is recursive. Next, using the definition of a
continuation in Section 3, we write the
continuation of each call to sum-iter
inside the definition
of sum-iter
. This definition consists of a single if
expression. The only time recursive calls are made to
sum-iter
is when i
is less than or equal to n
. The continuation
of the call to sum-iter
may be written as
(lambda(n) n)
This is the identity function. Since each continuation simply returns
its argument, there is no need to form the continuations in the first
place and it is possible for an optimizing compiler or interpreter
to derive an equivalent program which replaces the recursive calls
to sum-iter
with an iteration which directly forms the sum
of 0 + 1 + ...+ k with a single call to sum-iter
.