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 ...

Get Scala Functional Programming Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.