Learning Functional Programming in Scala Alvin Alexander
Total Page:16
File Type:pdf, Size:1020Kb
Learning Functional Programming in Scala Alvin Alexander A logical, step by step approach to learning functional programming Copyright Learning Functional Programming in Scala Copyright 2017 Alvin J. Alexander All rights reserved. No part of this book may be reproduced without prior written permission from the author. Disclaimer: This book is presented solely for educational purposes, and it’s also a work in progress. While best efforts have been used in prepar- ing this book, the author makes no representations or warranties of any kind and assume no liabilities of any kind with respect to the accuracy or completeness of the contents, and specifically disclaim any implied war- ranties of merchantability or fitness of use for a particular purpose. The author shall not be held liable or responsible to any person or entity with respect to any loss or incidental or consequential damages caused, or al- leged to have been caused, directly or indirectly, by the information or programs contained herein. Any use of this information is at your own risk. The advice and strategies contained herein may not be suitable for your situation. Version 0.1.1, published May 15, 2017 (The cover photo was taken on the Dalton Highway in Alaska, some- where between Fairbanks and Prudhoe Bay.) Contents 1 Changelog 1 2 Preface 3 3 Introduction (or, Why I Wrote This Book) 5 4 WhoThisBookisFor 11 5 Goals 15 6 Question Everything 23 7 Rules for Programming in this Book 33 8 One Rule for Reading this Book 39 9 What is “Functional Programming”? 41 10 What is This Lambda You Speak Of? 55 i ii CONTENTS 11 The Benefits of Functional Programming 73 12 Disadvantages of Functional Programming 99 13 The “Great FP Terminology Barrier” 123 14 Pure Functions 131 15 Grandma’s Cookies (and Pure Functions) 141 16 Benefits of Pure Functions 153 17 Pure Functions and I/O 163 18 Pure Function Signatures Tell All 173 19 Functional Programming as Algebra 181 20 A Note About Expression-Oriented Programming 197 21 Functional Programming is Like Unix Pipelines 203 22 Functions Are Variables, Too 225 CONTENTS iii 23 Using Methods As If They Were Functions 243 24 How to Write Functions That Take Functions as Input Parameters 255 25 How to Write a ‘map’ Function 279 26 How to Use By-Name Parameters 287 27 Functions Can Have Multiple Parameter Groups 303 28 Partially-Applied Functions (and Currying) 327 29 Recursion: Introduction 345 30 Recursion: Motivation 347 31 Recursion: Let’s Look at Lists 351 32 Recursion: How to Write a ‘sum’ Function 359 33 Recursion: How Recursive Function Calls Work 367 34 Visualizing the Recursive sum Function 373 iv CONTENTS 35 Recursion: A Conversation Between Two Developers 383 36 Recursion: Thinking Recursively 387 37 JVM Stacks and Stack Frames 397 38 A Visual Look at Stacks and Frames 407 39 Tail-Recursive Algorithms 417 40 A First Look at “State” 431 41 A Functional Game (With a Little Bit of State) 437 42 A Quick Review of Case Classes 455 43 Update as You Copy, Don’t Mutate 465 44 A Quick Review of for Expressions 477 45 How to Write a Class That Can Be Used in a for Expres- sion 487 46 Creating a Sequence Class to be Used in a for Compre- CONTENTS v hension 491 47 Making Sequence Work in a Simple for Loop 499 48 How To Make Sequence Work as a Single Generator in a for Expression 503 49 Enabling Filtering in a for Expression 509 50 How to Enable the Use of Multiple Generators in a for Expression 519 51 A Summary of the for Expression Lessons 531 52 Pure Functions Tell No Lies 535 53 Functional Error Handling (Option, Try, or Either) 543 54 Embrace The Idioms! 557 55 What to Think When You See That Opening Curly Brace561 A Explaining Scala’s val Function Syntax 581 vi CONTENTS B for expression translation examples 599 Chapter 1 Changelog Version 0.1.1 • released May 15, 2017 • all of the lessons following “The Great FP Terminology Barrier” are new • the book now contains 54 chapters and two appendices (about 400 pages of new content) • the book’s formatting is improved (but still needs more work) Version 0.1.0 • released April 23, 2017 • this was the initial release • it included the first eleven chapters, and was 219 pages long 1 2 Changelog Chapter 2 Preface While this Preface is a little unorthodox, I feel like it’s important to state why I’m releasing this book in the way that I’m releasing it. The first thing to say is that I’ve realized that it’s going to take another year before I can get this book to a point where I’m really going to love it. That being said, even though it’s definitely a “first draft” in its current state, I think there’s some material in here that can help programmers who are struggling to learn functional programming in Scala. I don’t want those people to have to wait another year when I can get something into their hands that can help them today. Therefore, I’ll be releasing a complete version of this book “as is” as soon as possible. You can think of it as an “alpha” version of what will eventu- ally be the final book. Release plan The book will initially be available only as a PDF because I don’t want to commit to print or MOBI (Amazon Kindle) versions of the book until it’s finished. My goal is to release a first, complete draft of the book by the end of May June, 2017. After that I also hope to provide updates to the book as they become available (i.e., as fast as I can write them). 3 4 Preface Pricing I haven’t set a price for the book yet, but since it’s an alpha version I’ll probably just charge a nominal fee, maybe $10-15 (U.S. currency). Hope- fully that will be enough to help me keep paying the bills. :) If it’s technically possible I’d like to make all updates to the alpha version to be free of charge to those who buy the book. My understanding is that I can do this on the platform I plan to use. “Updates” will include bug fixes, better organization, and better graphics, formatting, and improved wording. At some point I’ll have a “final” version of the book — at which time I’ll commit to print and MOBI, and the price will probably be $20 or more — but I haven’t put much thought into that yet. About the book I’m currently wrapping up the final lessons in the book, and I think the final alpha version will contain 90-110 small chapters. After the ini- tial background chapters, each lesson will generally cover a single topic, which is why there will be so many chapters. After several attempts at organizing the material, I think this is the best way to explain everything; it’s easier to understand the concepts when I introduce them one at a time, in small bites. All the best, Al Chapter 3 Introduction (or, Why I Wrote This Book) “So why do I write, torturing myself to put it down? Because in spite of myself I’ve learned some things.” Ralph Ellison The short version of “Why I wrote this book” is that I found that trying to learn functional programming in Scala was really hard, and I want to try to improve that situation. The longer answer goes like this … My programming background My degree is in aerospace engineering, so the only programming class I took in college was a FORTRAN class I was forced to take. After college I was one of the youngest people at the aerospace company I worked at, which meant that I’d have to maintain the software applications our group used. As a result, I became interested in programming, and then became interested in (a) “How can I write code faster?”, and then (b) “How can I write maintainable code?” 5 6 Introduction(or, Why I Wrote This Book) AfterthatItaughtmyselfhowtoprograminCbyreadingtheclassicbook, The C Programming Language by Kernighan and Ritchie, quickly fol- lowed by learning Object-Oriented Programming (OOP) with C++ and Java. That was followed by investigating other programming languages, including Perl, PHP, Ruby, Python, and more. Despite having exposure to all of these languages, I didn’t know anything about Functional Programming (FP) until I came across Google’s Guava project, which includes FP libraries for Java collections. Then, when I learned Scala and came to understand the methods in the Scala collec- tions’ classes, I saw that immutable values and pure functions had some really nice benefits, so I set out to learn more about this thing called Func- tional Programming. Trying to learn FP with Scala As I tried to learn about FP in Scala, I found that there weren’t any FP books or blogs that I liked — certainly nothing that catered to my “I’ve never heard of FP until recently” background. Everything I read was either (a) dry and theoretical, or (b) quickly jumped into topics I couldn’t understand. It seemed like people enjoyed writing words “monad” and “functor” and then watching me break out in a cold sweat. As I googled “scala fp” like a madman, I found a few useful blog posts here and there about functional programming in Scala — what I’ll call “Scala/FP” in this book — but those were too disconnected.