3. Functional data structures

 

In this chapter

  • Defining functional data structures using enum
  • Pattern matching and structural recursion
  • Writing polymorphic functions
  • Algebraic data types

We said in the introduction that functional programs don’t update variables or modify mutable data structures. This raises pressing questions: what sort of data structures can we use in functional programming, how do we define them in Scala, and how do we operate on them? In this chapter, we’ll learn the concept of functional data structures and how to work with them. We’ll use this as an opportunity to introduce how data types are defined in functional programming, learn about the related technique of pattern matching, and get 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. The answers are provided but try to work through each exercise before looking at the answer, as these techniques require practice to fully grasp. You can also consult our GitHub site (https://github.com/fpinscala/fpinscala; see the preface), which provides a build environment for the exercises and answers.

3.1 Defining functional data structures

3.2 Pattern matching

3.3 Data sharing in functional data structures

3.3.1 The efficiency of data sharing

3.3.2 Recursion over lists and generalizing to higher-order functions

3.3.3 More functions for working with lists

3.3.4 Loss of efficiency when assembling list functions from simpler components

3.4 Trees

3.5 Conclusion

3.6 Summary

3.7 Exercise Answers