[Index of Lectures]

[ L01 L02 L03 L04 L05 L06 L07 L08 L09 L10 L11 L12 L13 L14 L15 L16 L17 L18 L19 L20 L21 L22 L23 ]

Lecture 19—Tail Recursion 1

Before Lecture

Before this lecture you should:

During Lecture

The starters for this lecture are:

After Lecture

Tail recursion is different. We arrange for the recursion to just keep calling, calling, calling until it finds a result. Notice that in the sequence? example we did in lecture 18, we could easily have made that code tail recursive, by writing the recusive call using if instead of and:

    
       (if (= (first lon) (+ 1 prev)) ;exploit (use)
           (sequence? (rest lon)
                      (first lon))
           false)

That puts the recursive call to sequence? in tail position and makes the function tail recursive. So tail recursive functions on lists are fairly straightforward.

On trees on the other hand, tail recursion requires that we introduce a worklist, because when we go down one branch of a tree there are other branches that we need to come back to later.

Be sure to finish the m10-tr-trees-starter.rkt file as soon as you can. That will help you lock in how to work with tail recursive tree templates, just like you once locked in how to work with recursive list templates.

The solutions for this lecture are:

Be sure to complete the before lecture section of Lecture 20 before that lecture.