Learning Functional Programming in Scala Alvin Alexander

Learning Functional Programming in Scala Alvin Alexander

<p>Learning Functional Programming in Scala </p><p>Alvin Alexander </p><p><em>A logical, step by step approach to learning functional programming </em></p><p>Copyright </p><p><em>Learning Functional Programming in Scala </em></p><p>Copyright 2017 Alvin J. Alexander All rights reserved. No part of this book may be reproduced without prior written permission from the author. </p><p>Disclaimer: This book is presented solely for educational purposes, and it’s also a work in progress. While best efforts have been used in preparing 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 warranties 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 alleged to have been caused, directly or indirectly, by the information or programs contained herein.&nbsp;Any use of this information is at your own risk. The advice and strategies contained herein may not be suitable for your situation. </p><p>Version 0.1.1, published May 15, 2017 (The cover photo was taken on the Dalton Highway in Alaska, somewhere between Fairbanks and Prudhoe Bay.) </p><p>Contents </p><p><strong>1 Changelog 2 Preface </strong></p><p><strong>13</strong></p><p><strong>3 Introduction </strong><br><strong>(or, Why I Wrote This Book) </strong></p><p><strong>5</strong><br><strong>11 15 23 33 39 41 55 </strong></p><p><strong>4 Who&nbsp;This Book is For 5 Goals 6 Question&nbsp;Everything 7 Rules&nbsp;for Programming in this Book 8 One&nbsp;Rule for Reading this Book 9 What&nbsp;is “Functional Programming”? 10 What&nbsp;is This Lambda You Speak Of? </strong></p><p>iii </p><p><em>CONTENTS </em></p><p><strong>11 The&nbsp;Benefits of Functional Programming </strong></p><p><strong>73 </strong></p><p><strong>12 Disadvantages&nbsp;of Functional Programming 13 The&nbsp;“Great FP Terminology Barrier” 14 Pure&nbsp;Functions </strong></p><p><strong>99 </strong><br><strong>123 131 141 153 163 173 181 </strong></p><p><strong>15 Grandma’s&nbsp;Cookies (and Pure Functions) 16 Benefits&nbsp;of Pure Functions 17 Pure&nbsp;Functions and I/O 18 Pure&nbsp;Function Signatures Tell All 19 Functional&nbsp;Programming as Algebra 20 A&nbsp;Note About Expression-Oriented Programming 21 Functional&nbsp;Programming is Like Unix Pipelines 22 Functions&nbsp;Are Variables, Too </strong></p><p><strong>197 203 225 </strong></p><p><em>CONTENTS </em></p><p>iii </p><p><strong>23 Using&nbsp;Methods As If They Were Functions </strong></p><p><strong>243 </strong></p><p><strong>24 How&nbsp;to Write Functions That Take Functions as Input </strong><br><strong>Parameters </strong></p><p><strong>255 279 287 303 327 345 347 351 359 367 373 </strong></p><p><strong>25 How&nbsp;to Write a ‘map’ Function 26 How&nbsp;to Use By-Name Parameters 27 Functions&nbsp;Can Have Multiple Parameter Groups 28 Partially-Applied&nbsp;Functions (and Currying) 29 Recursion:&nbsp;Introduction 30 Recursion:&nbsp;Motivation 31 Recursion:&nbsp;Let’s Look at Lists 32 Recursion:&nbsp;How to Write a ‘sum’ Function 33 Recursion:&nbsp;How Recursive Function Calls Work 34 Visualizing&nbsp;the Recursive sum Function </strong></p><p>iv </p><p><em>CONTENTS </em></p><p><strong>35 Recursion:&nbsp;A Conversation Between Two Developers&nbsp;383 36 Recursion:&nbsp;Thinking Recursively 37 JVM&nbsp;Stacks and Stack Frames 38 A&nbsp;Visual Look at Stacks and Frames 39 Tail-Recursive&nbsp;Algorithms </strong></p><p><strong>387 397 407 417 431 437 455 465 477 </strong></p><p><strong>40 A&nbsp;First Look at “State” 41 A&nbsp;Functional Game (With a Little Bit of State) 42 A&nbsp;Quick Review of Case Classes 43 Update&nbsp;as You Copy, Don’t Mutate 44 A&nbsp;Quick Review of </strong>for <strong>Expressions 45 How&nbsp;to Write a Class That Can Be Used in a </strong>for <strong>Expres- sion </strong></p><p><strong>487 </strong></p><p><strong>46 Creating&nbsp;a Sequence Class to be Used in a </strong>for <strong>Compre- </strong></p><p><em>CONTENTS </em></p><p>v</p><p><strong>hension </strong></p><p><strong>491 </strong></p><p><strong>47 Making&nbsp;</strong>Sequence <strong>Work in a Simple </strong>for <strong>Loop </strong></p><p><strong>499 </strong></p><p><strong>48 How&nbsp;To Make </strong>Sequence <strong>Work as a Single Generator in a </strong>for <strong>Expression </strong></p><p><strong>503 509 </strong></p><p><strong>49 Enabling&nbsp;Filtering in a </strong>for <strong>Expression 50 How&nbsp;to Enable the Use of Multiple Generators in a </strong>for <br><strong>Expression </strong></p><p><strong>519 531 535 543 557 </strong></p><p><strong>51 A&nbsp;Summary of the </strong>for <strong>Expression Lessons 52 Pure&nbsp;Functions Tell No Lies 53 Functional&nbsp;Error Handling (Option, Try, or Either) 54 Embrace&nbsp;The Idioms! 55 What&nbsp;to Think When You See That Opening Curly Brace561 A Explaining&nbsp;Scala’s </strong>val <strong>Function Syntax </strong></p><p><strong>581 </strong></p><p>vi </p><p><em>CONTENTS </em></p><p></p><ul style="display: flex;"><li style="flex:1"><strong>B</strong></li><li style="flex:1">for <strong>expression translation examples </strong></li></ul><p></p><p><strong>599 </strong></p><p>Chapter 1 </p><p>Changelog </p><p>Version 0.1.1 </p><p>• released&nbsp;May 15, 2017 • all of the lessons following “The Great FP Terminology Barrier” are new </p><p>• the&nbsp;book now contains 54 chapters and two appendices (about 400 pages of new content) </p><p>• the&nbsp;book’s formatting is improved (but still needs more work) </p><p>Version 0.1.0 </p><p>• released&nbsp;April 23, 2017 • this&nbsp;was the initial release • it&nbsp;included the first eleven chapters, and was 219 pages long </p><p>1<br>2</p><p><em>Changelog </em></p><p>Chapter 2 </p><p>Preface </p><p>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. </p><p>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.&nbsp;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. </p><p>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 eventually be the final book. </p><p>Release plan </p><p>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. </p><p>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). </p><p>3<br>4</p><p><em>Preface </em></p><p>Pricing </p><p>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). Hopefully that will be enough to help me keep paying the bills. :) </p><p>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.&nbsp;“Updates” will include bug fixes, better organization, and better graphics, formatting, and improved wording. </p><p>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. </p><p>About the book </p><p>I’m currently wrapping up the final lessons in the book, and I think the final alpha version will contain 90-110 small chapters.&nbsp;After the initial background chapters, each lesson will generally cover a single topic, which is why there will be so many chapters.&nbsp;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. </p><p>All the best, Al </p><p>Chapter 3 </p><p>Introduction (or, Why I Wrote This Book) </p><p>“So why do I write, torturing myself to put it down? Because in spite of myself I’ve learned some things.” </p><p>Ralph Ellison <br>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. </p><p>The longer answer goes like this … </p><p>My programming background </p><p>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?” </p><p>5<br>6</p><p><em>Introduction(o r , W hy I Wrote This Book) </em></p><p>After that I taught myself how to program in C by reading the classic book, <a href="/goto?url=http://amzn.to/2aeEAZa" target="_blank">The C Programming Language </a>by Kernighan and Ritchie, quickly followed 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. </p><p>Despite having exposure to all of these languages, I didn’t know anything about Functional Programming (FP) until I came across <a href="/goto?url=https://github.com/google/guava/wiki" target="_blank">Google’s Guava </a><a href="/goto?url=https://github.com/google/guava/wiki" target="_blank">project</a>, which includes FP libraries for Java collections.&nbsp;Then, when I learned <a href="/goto?url=http://scala-lang.org/" target="_blank">Scala </a>and came to understand the methods in the Scala collections’ 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 <em>Func- </em></p><p><em>tional Programming</em>. </p><p>Trying to learn FP with Scala </p><p>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.&nbsp;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. </p><p>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. One article covered Topic A, another covered Topic Z, and they were written by different authors with different experiences, so it was hard to find my way from A to Z. Besides being disjointed, they were often incomplete, or maybe they just assumed that I had some piece of knowledge that I didn’t really have. <br>7<br>Another stumbling block is that experienced FP developers use generic types a <em>lot</em>. They&nbsp;also use the word “easy” when describing their code, as though saying “easy” is some sort of Jedi mind trick.&nbsp;For instance, this code — which I’ll break down as you go through this book — was introduced with the text, “it’s very easy to access and modify state”: </p><p>def updateHealth(delta: Int): Game[Int] = <br>StateT[IO, GameState, Int] { (s: GameState) =&gt; </p><p>val newHealth = s.player.health + delta IO((s.copy(player = s.player.copy(health = newHealth)), newHealth)) </p><p>}</p><p>I don’t know about you, but the first time I saw that code, the word <em>easy </em>is not what came to mind. What came to my mind were things like, “PHP is easy. Using setter methods to modify state is easy. Whatever that is … that’s not easy.” </p><p>Another problem with almost all of the Scala/FP resources is that they don’t discuss functional input/output (I/O), or how to work with user interfaces. In this book I don’t shy away from those topics: I write what I know about both of them. </p><p>Learning Haskell to learn FP </p><p>In the end, the only way I could learn FP was to buy four <a href="/goto?url=https://www.haskell.org" target="_blank">Haskell </a>books, take a few weeks off from my regular work, and teach myself Haskell. Because Haskell is a “pure” FP language — and because most experienced Scala/FP developers spoke glowingly about Haskell — I assumed that by learning Haskell I could learn FP. 8</p><p><em>Introduction(o r , W hy I Wrote This Book) </em></p><p>That turned out to be true. In Haskell the only way you can write code is by using FP concepts, so you can’t bail out and take shortcuts when things get difficult.&nbsp;Because everything in Haskell is immutable, I was forced to learn about topics like recursion that I had avoided for most of my programming life. In the <em>beginning </em>this made things more difficult, but in the <em>end </em>I learned about the benefits of the new approaches I was forced to learn. </p><p>Once I understood Haskell, I went back to the Scala resources that I didn’t like before and they suddenly made sense(!).&nbsp;But again, this only </p><p>happened <em>after I took the time to learn Haskell</em>, a language I didn’t plan on </p><p>using in my work. </p><p>The purpose of this book </p><p>Therefore, my reasons for writing this book are: <br>• To&nbsp;save you the time of having to try to understand many different, unorganized, inconsistent Scala/FP blog posts </p><p>• To&nbsp;save you the time of “having to learn Haskell to learn FP,” and then having to translate that Haskell knowledge back to Scala </p><p>• To&nbsp;try to make learning Scala/FP as simple as possible <br>9</p><p>Don’t get my statements about Haskell wrong: In the end, Haskell turned out to be a really interesting and even fun programming language.&nbsp;If I knew more about its libraries — or if it ran on the JVM and I could use the wealth of existing JVM libraries out there (most of which are not written in an FP style) — I’d be interested in trying to use it. That being said, I hope I can teach you what I learned about FP using only Scala. </p><p>As a potential benefit of this book, if you already know Scala/OOP and are interested in learning Haskell, you can learn Scala/FP from this book, and then you’ll find it much easier to understand Haskell. </p><p>10 </p><p><em>Introduction(o r , W hy I Wrote This Book) </em></p>

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    619 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us