Tail Recursion
Look again at the stack usage of that new version of factorial
we introduced:
| | | | |
|(fact 4)|(fact-it 1 1 4)|(fact-it 1 2 4)|(fact-it 2 3 4)| (continued...)
----------------------------------------------------------
| | | |
|(fact-it 6 4 4)|(fact-it 24 5 4)| 24 |
---------------------------------------
The shape is just a horizontal line, which is characteristic of
what's called a "linear iterative process" (note that the process
can be iterative, referring to how the shape is produced, even though
the procedure itself is defined recursively).
To accomplish this, we used a type of recursion called "tail
recursion". In LISP, we obtain tail recursion by making sure
that the step in our procedure which is the recursive step
does not have any "work" being done "outside" the recursive
function call. Compare the corresponding steps from the two
different function definitions. Here's the first version:
(T (* n (factorial (- n 1))))))
That "(* n " part is what was killing us in terms of memory
usage. This kind of recursion is called "augmenting
recursion", meaning that there's some additional computation
added on to the recursive call, and that makes the program
stack grow. In the tail recursive version, however, there's
no augmenting recursion:
(T (factorial-iterative (* counter product)
(+ counter 1)
max-count))))
All the computation is done within the arguments to the
function call, and so the substitutions are one-for-one and
don't cause any growth of the program stack.
Here's a slightly different perspective which may help you
understand the difference between these two types of
recursion. The first version of the factorial function
postponed arithmetic operations as it progressed, and to
postpone those operations, LISP had to remember what those
operations were. To remember all that stuff, LISP had to
use a chunk of memory on the program stack for each postponed
operation.
But when the tail-recursive version of factorial is running,
no arithmetic operations are being postponed. All
computations are being done as they're needed, so no
operations must be remembered, and consequently there's
no corresponding growth in usage of the program stack.
In order to make this work, though, we had to introduce the
equivalent of variables as place holders for these embedded
computations, and we did this by introducing some additional
arguments. Those arguments in this case were established
through the creation of a helping function, which initializes
the arguments being used as variables:
(defun factorial (n)
(factorial-iterative 1 1 n))
The arguments themselves take on the roles of the sorts of
things you'd expect to see in a traditional iterative
solution:
(defun factorial-iterative (product counter max-count)
...
Here, "product" is used as the place where you store your
cumulative product, and it is initialized to the
multiplicative identity (i.e., 1). "counter" is just your
index variable, and "max-count" is the limit on the number of
"iterations" you want this thing to perform.
So, it may look like iteration, but tail recursion is most
definitely a clever and successful attempt to reap some
of the resource savings of iterative solutions while maintaining
design qualities of the functional programming paradigm.
We gain the advantages of iterative solutions without the
corresponding increase in complexity. What kind of complexity?
Well, just think about this for a minute. If I'm debugging
a recursive function that's constructed within the constraints
of the functional programming paradigm (like "factorial-iterative"),
I know that those "variables" won't be changing value while I
examine the execution of that function. That's gonna make my life
easier, in the short run as well as the long run. On the other
hand, if I'm debugging the traditional, loop-based, side-effects-laden
equivalent of "factorial-iterative", I've got three variables
which *are* changing values as that procedure is running, and
that makes it harder for me to follow what's going on, and therefore
harder for me to make sure that the procedure actually does what I
want it to do.
Sometimes the tail recursive solutions are not immediately
obvious, and sometimes they just seem natural. Just take
a look at the "my-member" function to see just how obvious the tail
recursive solution can be. Like many things in this course, it's not
especially hard, but it does require a different slant on thinking
about the problem, and again like many things in this course, it
gets better with practice. In any case, going after
the tail recursive solution is worthwhile, for reasons
we've shown above. Also, some LISP systems have the ability to
recognize and further optimize tail recursive functions. The
object code that is produced is actually a simple loop (which
you never see) with variables corresponding to the arguments being
passed in the recursive function call. This gives you the elegant
expressiveness of recursion with the speed of loops or
whatever your flavor of iterative control structure might be.
You get all the good stuff, and none of the bad stuff.
You might argue, as students occasionally do, that tail recursive
solutions are harder to read, and I believe that's true for
new LISP programmers. But as you gain more experience,
the tail recursive solution becomes just another programming
cliche and no longer causes any difficulty in understanding
what's going on. Remember that lots of tasks look difficult
the first time you encounter them, but over time they become
second nature. When you were real little, your primary mode
of locomotion was crawling. At some point you tried standing
up and walking, and this was undoubtedly much more difficult
than crawling at first. But you kept at it, and now you get
around by walking instead of crawling (except perhaps the
morning after one of those particularly intense frat parties).
The moral is simply that if you practice, you get better.
Students will sometimes overgeneralize the "factorial-iterative"
example and assume that all tail recursive functions require some
helping or auxiliary function. Our definition of "my-member"
didn't require any helping function though, and it's certainly
tail recursive. The helping function is only necessary if you
need to introduce "variables" as additional arguments, so don't
get carried away with the helping functions.
The myth of efficiency
One of the big myths that is constantly perpetuated in the
religious wars about programming paradigms and programming
languages is that functional programming in general (and LISP
in particular) is to be avoided because of all this recursion
stuff. It's hard to learn, they say, and it's obviously
inefficient.
It may be true that the concept of recursion itself is
difficult to grasp, but for most folks it seems that the real
problem is that they've been trained to think about
repetitive computations in a certain way, using index
variables and loops and so on. That training interferes with
thinking about the same problems in different ways; you'll
feel that urge to fall back on old familiar habits. That
urge should diminish as you become more comfortable with the
paradigm.
But the knock on efficiency is in fact nothing more than
mythology spread by folks who never learned the whole story.
As we've just seen:
1) If I'm thinking about it instead of acting like I'm brain
dead, I can use tail recursion and get very efficient
results. Remember that brain-dead programmers make
inefficient programs, regardless of their choice of
language or paradigm.
2) Again, efficiency of the programmer, especially on the
back end of the software life cycle, is greatly improved
by the use of recursion (and other functional programming
ideas), assuming of course that the other folks who read
your code also aren't brain dead.
Recursion examples
After exploring the factorial function in great detail, we
went over a bunch of examples, comparing augmenting recursion
examples to tail recursion examples. Our first example was "length":
(defun my-length (input-list)
(cond ((null input-list) 0)
(T (+ 1 (my-length (rest input-list))))))
Note how the augmenting recursion solution maps onto an inductive proof.
The ((null input-list) 0) corresponds to the base case. The
(my-length (rest input-list)) maps onto assuming the proof holds
for the Nth case. And the (+ 1 (...)) wrapper on the call to
"my-length" maps onto proving the N+1th case. Now here's the
tail recursion version of the same thing:
(defun my-length (input-list)
(my-length-helper input-list 0))
(defun my-length-helper (input-list counter)
(cond ((null input-list) counter)
(T (my-length-helper (rest input-list) (+ 1 counter)))))
That one was pretty simple. Here's a more complicated problem.
The "substitute" function works like this:
? (substitute 'x 'a '(a b (a) c a))
(X B (A) C X)
Here's the augmenting recursion approach:
(defun my-substitute (new old input-list)
(cond ((null input-list) nil)
((eql old (first input-list))
(cons new (my-substitute new old (rest input-list))))
(T (cons (first input-list)
(my-substitute new old (rest input-list))))))
We'll do more examples next class.
Lecture notes by Kurt Eiselt, 1998.
Minor changes / additions by Brian McNamara, 1998.
Last updated on
Thu Jul 9 13:48:27 EDT 1998
by Brian McNamara