Chapter 3. Recursion and Chasing your Own Tail
In the first chapter, we wrote a nested method, groupThem()
, that called itself. In the second chapter, the BST traversal method is similar to the nested method. We saw that the method calls itself to traverse the children. A method calling itself is recursion. In the previous chapter, we also touched upon tail recursion and Scala's @tailrec
annotation.
Let's look at these concepts more closely and see how all these help us write succinct code, and how going recursive promotes immutability. In this chapter, we will first look at recursive structures—a structure is recursive if the shape of the whole recurs in the shape of the parts. We will then look at how Scala's pattern matching helps us to work on the composing parts. Next, we will take a look at a possible problem with very large structures and the mechanism to deal with them—namely tail call optimization (TCO) and @tailrec
annotations. Finally, we...