This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do.
To my father, who taught me to care about the work.
Introduction
Many, many of the legendary programmers know manyprogramming languages. What they know from one languagehelps them write better code in another one. But its notreally the language that matters: adding knowledge of C# toyour knowledge of Java doesnt make you much better. Thoselanguages are too similar: they encourage you to look atproblems in pretty much the same way. You need to knowlanguages that conceptualize both problems and solutions insubstantially different ways.
Once upon a time, object-oriented programming was a radicaldeparture from what most programmers knew. So learning itwas both hard and mind-expanding. Nowadays, the OO style (orsome approximation to it) isthe dominant one, so ambitious people need toseek out different styles.
The functional programming style is nicely different fromthe OO style, but there are many interesting points ofcomparison between them. This book aims to teach you keyelements of the functional style, helping you take them backto your OO programming.
Theres a bit more, though: although the functional stylehas been around for many years, its recently become trendy,partly because language implementations keep improving, andpartly because functional languages are better suited forthe problem of running one program on multiple cores.Some trends with a lot of excitement behind themwither, but others (like object-oriented programming)succeed immensely. If the functional style becomescommonplace, this book will position you to be around theleading edge of that wave.
There are many functional languages. There are arguments forlearning the purest of them (Haskell, probably). But itsalso worthwhile to learn a slightly-less-pure language ifthere are more jobs available for it or more opportunitiesto fold it into your existing projects. According thatstandard, Clojure and Scalaboth of which piggyback on theJava runtimestandout. This book will use Clojure.
Prerequisites
You need to know at least one object-oriented programminglanguage. Anything will do: Objective-C, C++, C#, Java,Ruby, Python: you name it.
You need to be able to start a program from the commandline.
The flow of the book
Ill start by teaching you , the use of general-purpose data types).
After about 50 pages of object system implementation, wellhave implemented an object system something like Javas, andwell alsohave exhausted the examples usefulness for teachingfunctional style. Those interested in object models as atopic in themselves can temporarily branch off to the optional , which fleshes out the Java-like object model into oneinspired by Rubys.
Part 2, , iswhere I fulfill the promise to show you how functionallanguages help you conceptualize both problems and solutions insubstantially different ways.
- The first two chapters are about functional programmershabit of using through a series offunctions. Youll have seen that in Part 1, but thesechapters focus on it explicitly and also cover how thisstyle can be hidden inside an object-oriented program.
- The nextchapter, , shows one of the main tools ofabstraction for functional programs: functionsthat create other functions in a parameterized way.
- When data is flowing through functions,
if
statementsand loops complicate the code. The describes more interesting ones andwill give you a deeper understanding of how they work. - The languages youre used to dont allow you to change thevalue of 1 to be, say, 2. Clojure, along with many other functional languages, extends the same immutability to all data. Once a list is created, you cant add to it or change it. In Part 1, youll have seen thats not as crazy as it seemsat least for relatively flat data structures. However, things get more difficult when working with deeper structures. New approaches are needed for tasks like change that 4 way down in that tree to a 5. In the , Ill show how the zipper datatype and its associated functions can be used for just such a task. Ill also work through the implementation of zippers, for two reasons:
First, zippers illustrate how functional programmers often solve problems by writing code that builds a data structure that represents a computation, then pass that structure around to be used only when (and if) its needed.
Second, it provides a more complex example of using basic data types than does the first chapter. Well see how its useful to think about the shape of the data rather than its type or class.
- Throughout the book, I will have teased you with whatseems to be deliberately and ridiculously inefficient code., Ill show how that apparent inefficiency is an illusion. In reality, wererelying on the runtime to make two kindsof optimizations for us:
Lazy evaluation: In functional languages, its common for some or all values to be lazy, meaning that they (and their component parts) are only calculated when demanded. Ill show how this collapses what appear to be many loops into just one. More importantly, Ill show how it allows you to let free of the idea that you must be able to calculate in advance how much data youll need. Instead, you can just ask for all of it and let the runtime avoid generating too much.
Sharing structure behind the scenes: While you cant mutate functional data structures, the language runtime can. Ill show an example of how the runtime can optimize away the wasteful copying your program appears to be doing. Ill also discuss the implications of adopting immutability in object-oriented programs.
- When you start looking at data in terms of its shape, it begins to seemreasonable to have functions decide what code to run basednot on explicit
if
tests but rather on . - support a verb-centered way ofthinking about the world: there are actions that can applyvery broadly. The specifics of an action depend on someproperties (determined at runtime) of the values itsapplied to. Generic functions are the flip side of thenoun-centered approach taken by object-orientedlanguages.
That finishes the book, except for the optional parts onobject models and monads.
About the exercises
Ive taught some of the material in this book in a two-daytutorial. Most of the classroom time is spent doingexercises. They add a lot of value; you should dothem. Failing that, you should at least read them andperhaps look at my solutions, as Im not shy about havinglater sections build on functions defined by the exercises.
You can find exercise solutions in this books Githubrepository. If you use theGit version management tool, you can fetch the code likethis:
1
git clone git://github.com/marick/fp-oo.git
You can also use your browser to download Zip or Tarfiles.
At last resort, you can browse the repository through yourbrowser. The exercise descriptions include a clickable link to the solutions.