Fundamentals of CS I (CS151 2001S) : Outlines
[Current]
[Discussions]
[Glance]
[Honesty]
[Instructions]
[Links]
[News]
[Search]
[Syllabus]
Primary
[Examples]
[Exams]
[Handouts]
[Homework]
[Labs]
[Outlines]
[Quizzes]
[Readings]
[Reference]
Sets
[Blackboard]
[Scheme Report]
[SamR's Schedule]
[Rebelsky/Fall 2000]
[Walker/Fall2000]
[Stone/Spring2000]
Links
Reading: Tail Recursion. Lab: Tail Recursion. Back to Script-Fu Concluded. On to Tail Recursion, Continued.
Held Monday, April 9, 2001
Summary
Today we revisit recursion and consider a more efficient way to write recursive procedures. This new technique is called tail recursion.
Notes
(define intersect
(lambda (set1 set2)
((remove (complement (right-section member set2))) set1)))
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)
(suml-helper values 0)))
(define suml-helper
(lambda (remaining-values partial-sum)
(if (null? remaining-values) partial-sum
(suml-helper (cdr remaining-values)
(+ partial-sum
(car remaining-values))))))
(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 Script-Fu Concluded. On to Tail Recursion, Continued.
[Current]
[Discussions]
[Glance]
[Honesty]
[Instructions]
[Links]
[News]
[Search]
[Syllabus]
Primary
[Examples]
[Exams]
[Handouts]
[Homework]
[Labs]
[Outlines]
[Quizzes]
[Readings]
[Reference]
Sets
[Blackboard]
[Scheme Report]
[SamR's Schedule]
[Rebelsky/Fall 2000]
[Walker/Fall2000]
[Stone/Spring2000]
Links
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 Wed May 5 12:15:06 2004.
This page may be found at http://www.cs.grinnell.edu/~rebelsky/Courses/CS151/2001S/outline.37.html.
You may validate
this page's HTML.
The source was last modified Tue Jan 23 16:01:58 2001.