[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 20—Tail Recursion 2

Before Lecture

Be sure to carefully review the material from Lecture 19. Expect lecture 20 to build on that material and expect clicker questions based on that material.

During Lecture

The first part of this lecture does not use a starter file. For the second part of the lecture the starter file is:

After Lecture

In this lecture we built on the expert thinking skills you have been developing throughout the course. We saw how to read a complex function, and use our knowledge of the templates and how accumulators work to slice it up into different aspects of its behaviour (colors). We reconstructed the accumulator types and invariants and used that to understand the behaviour of 2 functions.

One function traversed the tree using standard recursion; the other uses tail recursion. Both functions maintained an accumulator that was consed onto in each recursive call. But because of the difference in how the two kinds of recursion traverse the graph, the two accumulators accumulate different values event though the update code for both looks the same. It is important to understand the different values these accumulators take on, and is important to follow our naming convention: We call it path in the ordinary recursion, and visited in the tail recursion.

We then moved on to module 11 and jumped into the maze solver again. We updated the program to be able to move in all four directions but found that it ran forever. That happens because the program is now traversing a directed graph, not a tree, and directed graphs can have cycles, which can lead our solver to go around and around in circles forever.

The solutions for today's lecture are:

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