Fundamentals of Computer Science I (CS151 2003F)
[Skip to Body]
Primary:
[Front Door]
[Current]
[Glance]
-
[Honesty]
[Instructions]
[Links]
[Guidelines for Lab Writeups]
Groupings:
[EBoards]
[Examples]
[Exams]
[Handouts]
[Homework]
[Labs]
[Outlines]
[Readings]
[Reference]
Misc:
[Scheme Report]
[Glimmer Scheme Reference]
[CSC151.01 (Gum)]
[CSC151 2003S]
[CSC151 2002F]
[SamR]
Back to Variable-Arity Procedures. On to Association Lists.
Held: Thursday, 13 November 2003
Summary: Today we revisit recursion and consider a more efficient way to write recursive procedures. This technique is called tail recursion.
Related Pages:
Assignments
Notes:
Overview:
add-to-all, factorial,
traditional right-associative sum.
member?, the left-associative sum.
sum (in class).
(define sumr
(lambda (values)
(if (null? values) 0
(+ (car values) (sumr (cdr values))))))
+ Version 2, left associative, tail recursive.
(define suml
(lambda (values)
(letrec ((suml-helper
(lambda (remaining-values partial-sum)
(if (null? remaining-values) partial-sum
(suml-helper (cdr remaining-values)
(+ partial-sum
(car remaining-values)))))))
(suml-helper values 0))))
(1 2 3 4) and see if one seems
to be easier to deal with.
(sumr (1 2 3 4)) --> (+ 1 (sumr (2 3 4))) --> (+ 1 (+ 2 (sumr (3 4)))) --> (+ 1 (+ 2 (+ 3 (sumr (4))))) --> (+ 1 (+ 2 (+ 3 (+ 4 (sumr ()))))) --> (+ 1 (+ 2 (+ 3 (+ 4 0)))) --> (+ 1 (+ 2 (+ 3 4))) --> (+ 1 (+ 2 7)) --> (+ 1 9) --> 10
(suml (1 2 3 4)) --> (suml-helper (1 2 3 4) 0) --> (suml-helper (2 3 4) 1) --> (suml-helper (3 4) 3) --> (suml-helper (4) 6) --> (suml-helper () 10) --> 10
things to do once the recursion reaches the base case.
suml:
accumulatespartial solutions. Hence, we often call it an accumulator.
oldbase case (the one in the non-tail-recursive procedure).
Back to Variable-Arity Procedures. On to Association Lists.
[Skip to Body]
Primary:
[Front Door]
[Current]
[Glance]
-
[Honesty]
[Instructions]
[Links]
[Guidelines for Lab Writeups]
Groupings:
[EBoards]
[Examples]
[Exams]
[Handouts]
[Homework]
[Labs]
[Outlines]
[Readings]
[Reference]
Misc:
[Scheme Report]
[Glimmer Scheme Reference]
[CSC151.01 (Gum)]
[CSC151 2003S]
[CSC151 2002F]
[SamR]
Disclaimer:
I usually create these pages on the fly
, which means that I rarely
proofread them and they may contain bad grammar and incorrect details.
It also means that I tend to update them regularly (see the history for
more details). Feel free to contact me with any suggestions for changes.
This document was generated by
Siteweaver on Tue Dec 9 13:59:55 2003.
The source to the document was last modified on Mon Sep 1 13:30:51 2003.
This document may be found at http://www.cs.grinnell.edu/~rebelsky/Courses/CS151/2003F/Outlines/outline.41.html.
You may wish to
validate this document's HTML
;
;
Check with Bobby