This chapter covers:
- Defining functional data structures using algebraic data types
- Demonstrating how branching logic can be written in a single expression
- Sharing data using functional data structures
- Using list recursion and generalising to higher-order functions
- Practice writing and generalizing pure functions
- Implementing
List
andTree
data structures from first principals
We said in chapter 1 that functional programs don’t update variables or modify mutable data structures. The emphasis on keeping variables immutable raises pressing questions: what sort of data structures can we use in functional programming, how do we define them in Kotlin, and how do we operate on them?
In this chapter, we’ll learn the concept of functional data structures by writing our own implementations of a singly linked list and tree. We will also learn about the related processing technique of matching, and get lots of practice writing and generalizing pure functions.
This chapter has a lot of exercises, particularly to help with this last point—writing and generalizing pure functions. Some of these exercises may be challenging. Always try your best to solve them by yourself, and if you really get stuck, you may consult appendix A at the back of the book. Try to use this resource only when you absolutely must! All the source code for the samples and exercises are also available in our GitHub repository (github.com/fpinkotlin/fpinkotlin).