Functional Programming in Scala (2015)
Preface
Writing good software is hard. After years of struggling with other approaches, both of us discovered and fell in love with functional programming (FP). Though the FP approach is different, we came to appreciate how the discipline leads to a coherent, composable, and beautiful way of writing programs.
Both of us participated in the Boston Area Scala Enthusiasts, a group that met regularly in Cambridge. When the group first started, it mainly consisted of Java programmers who were looking for something better. Many expressed frustration that there wasn’t a clear way to learn how to take advantage of FP in Scala. We could empathize—we had both learned FP somewhat haphazardly, by writing lots of functional code, talking to and learning from other Scala and Haskell programmers, and reading a patchwork of different articles, blog posts, and books. It felt like there should be an easier way. In April 2010 one of the group’s organizers, Nermin Šerifović, suggested that we write a book specifically on the topic of FP in Scala. Based on our learning experiences, we had a clear idea of the kind of book we wanted to write, and we thought it would be quick and easy. More than four years later, we think we have created a good book. It’s the book we wish had existed when we were learning functional programming.
We hope to convey in this book some of the excitement that we felt when we were first discovering FP.
About this Book
This is not a book about Scala. This book is an introduction to functional programming (FP), a radical, principled approach to writing software. We use Scala as the vehicle to get there, but you can apply the lessons herein to programming in any language. As you work through this book, our goal is for you to gain a firm grasp of functional programming concepts, become comfortable writing purely functional programs, and be able to absorb new material on the subject, beyond what we cover here.
How this book is structured
The book is organized into four parts. In part 1, we talk about exactly what functional programming is and introduce some core concepts. The chapters in part 1 give an overview of fundamental techniques like how to organize small functional programs, define purely functional data structures, handle errors, and deal with state.
Building on this foundation, part 2 is a series of tutorials on functional design. We work through some examples of practical functional libraries, laying bare the thought process that goes into designing them.
While working through the libraries in part 2, it will become clear to you that these libraries follow certain patterns and contain some duplication. This will highlight the need for new and higher abstractions for writing more generalized libraries, and we introduce those abstractions in part 3. These are very powerful tools for reasoning about your code. Once you master them, they hold the promise of making you extraordinarily productive as a programmer.
Part 4 then bridges the remainder of the gap towards writing real-world applications that perform I/O (like working with databases, files, or video displays) and make use of mutable state, all in a purely functional way.
Throughout the book, we rely heavily on programming exercises, carefully sequenced to help you internalize the material. To understand functional programming, it’s not enough to learn the theory abstractly. You have to fire up your text editor and write some code. You have to take the theory that you have learned and put it into practice in your work.
We’ve also provided online notes for all the chapters. Each chapter has a section with discussion related to that chapter, along with links to further material. These chapter notes are meant to be expanded by the community of readers, and are available as an editable wiki athttps://github.com/fpinscala/fpinscala/wiki.
Audience
This book is intended for readers with at least some programming experience. We had a particular kind of reader in mind while writing the book—an intermediate-level Java or C programmer who is curious about functional programming. But we believe this book is well suited for programmers coming from any language, at any level of experience.
Prior expertise is not as important as motivation and curiosity. Functional programming is a lot of fun, but it’s a challenging topic. It may be especially challenging for the most experienced programmers, because it requires such a different way of thinking than they might be used to. No matter how long you have been programming, you must come prepared to be a beginner once again.
This book does not require any prior experience with Scala, but we won’t spend a lot of time and space discussing Scala’s syntax and language features. Instead we will introduce them as we go, with minimal ceremony, mostly as a consequence of covering other material. These introductions to Scala should be enough to get you started with the exercises. If you have further questions about the Scala language, you should supplement your reading with another book on Scala (http://scala-lang.org/documentation/books.html) or look up specific questions in the Scala language documentation (http://scala-lang.org/documentation/).
How to read this book
Although the book can be read sequentially straight through, the sequencing of the four parts is designed so that you can comfortably break between them, apply what you have learned to your own work, and then come back later for the next part. For example, the material in part 4 will make the most sense after you have a strong familiarity with the functional style of programming developed in parts 1, 2, and 3. After part 3, it may be a good idea to take a break and try getting more practice writing functional programs beyond the exercises we work on in the chapters. Of course, this is ultimately up to you.
Most chapters in this book have a similar structure. We introduce some new idea or technique, explain it with an example, and then work through a number of exercises. We strongly suggest that you download the exercise source code and do the exercises as you go through each chapter. Exercises, hints, and answers are all available at https://github.com/fpinscala/fpinscla. We also encourage you to visit the scala-functional Google group (https://groups.google.com/forum/#!topic/scala-functional/) and the #fp-in-scala IRC channel on irc.freenode.net for questions and discussion.
Exercises are marked for both their difficulty and importance. We will mark exercises that we think are hard or that we consider to be optional to understanding the material. The hard designation is our effort to give you some idea of what to expect—it is only our guess and you may find some unmarked questions difficult and some questions marked hard to be quite easy. The optional designation is for exercises that are informative but can be skipped without impeding your ability to follow further material. The exercises have the following icons in front of them to denote whether or not they are optional:
Exercise 1
A filled-in square next to an exercise means the exercise is critical.
Exercise 2
An open square means the exercise is optional.
Examples are presented throughout the book, and they are meant to be tried rather than just read. Before you begin, you should have the Scala interpreter running and ready. We encourage you to experiment on your own with variations of what you see in the examples. A good way to understand something is to change it slightly and see how the change affects the outcome.
Sometimes we will show a Scala interpreter session to demonstrate the result of running or evaluating some code. This will be marked by lines beginning with the scala> prompt of the interpreter. Code that follows this prompt is to be typed or pasted into the interpreter, and the line just below will show the interpreter’s response, like this:
scala> println("Hello, World!")
Hello, World!
Code conventions and downloads
All source code in listings or in text is in a fixed-width font like this to separate it from ordinary text. Key words in Scala are set in bold fixed-width font like this. Code annotations accompany many of the listings, highlighting important concepts.
To download the source code for the examples in the book, the exercise code, and the chapter notes, please go to https://github.com/fpinscala/fpinscala or to the publisher’s website at www.manning.com/FunctionalProgramminginScala.
Setting expectations
Although functional programming has a profound impact on the way we write software at every level, it takes time to build up to that. It’s an incremental process. Don’t expect to be blown away by how amazing functional programming is right in the first chapter. The principles laid out in the beginning are quite subtle, and may even seem like they’re just common sense. If you think to yourself “that’s something I can already do without knowing FP,” then that’s great! That’s exactly the point. Most programmers are already doing FP to some extent, without even knowing it. Many things that most people consider to be best practices (like making a function have only a single responsibility, or making data immutable) are implied by accepting the premise of functional programming. We are simply taking the principles underlying those best practices and carrying them all the way to their logical conclusion.
It’s highly likely that in reading this book, you will simultaneously learn both Scala syntax and functional programming. As a result, at first it may seem to you that the code looks very alien, the techniques are unnatural, and the exercises are brain-bending. That is perfectly normal. Do not be deterred. If you get stuck, look at the hints and answers,[1] or take your questions to the Google Group (https://groups.google.com/forum/#!topic/scala-functional/) or the IRC channel (#fp-in-scala on irc.freenode.net).
1 https://github.com/fpinscala/fpinscala.
Above all, we hope that this book will be a fun and rewarding experience for you, and that functional programming makes your work easier and more enjoyable as it has done for us. This book’s purpose, when all is said and done, is to help you be more productive in your work. It should make you feel less like the software you are writing is a collection of dirty hacks, and more like you are creating a thing of beauty and utility.