a. Go over the short reading on tail recursion.
b. Start DrScheme.
Identify three (or more) tail-recursive procedures you've already written.
In DrScheme, you can find out how long it takes to evaluate an
expression by using
(time expression). The
time procedure prints out the time it takes to evaluate
and then returns the value computed. If you care only about the
time it takes, you can write
> (let ((junk (time expression))))
a. Try the two versions of
factorial on some large numbers.
Does one seem to be faster than the other?
b. Try the three versions of
add-to-all on some lists
of varying sizes (you'll probably need at least a hundred values in
each list, and possibly more) until you can determine a difference
in running times.
Write a tail-recursive
Define a tail-recursive procedure
index that has two
arguments, an item
a and a list of items
and returns the index of
ls, that is, the
zero-based location of
ls. If the item
is not in the list, the procedure returns -1. Test your procedure on:
(index 3 (list 1 2 3 4 5 6)) --> 2 (index 'so (list 'do 're 'mi 'fa 'so 'la 'ti 'do)) --> 4 (index "a" (list "b" "c" "d")) --> -1 (index 'cat null) --> -1
Define and test a tail-recursive version of
Write your own tail-recursive version of
This is an optional extra-credit exercise.
Here's a non-tail-recursive version of
(define append (lambda (list-one list-two) (if (null? list-one) list-two (cons (car list-one) (append (cdr list-one) list-two)))))
a. Write your own tail-recursive version.
b. Determine experimentally which of the three versions (built-in, given above, tail-recursive) is fastest.
Monday, 30 October 2000 [Samuel A. Rebelsky]
Sunday, 8 April 2001 [Samuel A. Rebelsky]
add-to-endafter adding the answer to the reading.
Disclaimer: I usually create these pages on the fly. This means that they are rarely proofread and may contain bad grammar and incorrect details. It also means that I may update them regularly (see the history for more details). Feel free to contact me with any suggestions for changes.
This page was generated by Siteweaver on Thu May 3 23:08:07 2001.
This page may be found at
You may validate this page's HTML.
The source was last modified Sun Apr 8 22:07:17 2001.