Functional Programming in Scala, Second Edition (MEAP V08) Michael Pilquist All Chapters Instant Download
Functional Programming in Scala, Second Edition (MEAP V08) Michael Pilquist All Chapters Instant Download
com
https://ebookmeta.com/product/functional-programming-in-
scala-second-edition-meap-v08-michael-pilquist/
OR CLICK BUTTON
DOWNLOAD NOW
https://ebookmeta.com/product/programming-scala-scalability-
functional-programming-objects-third-edition-wampler-dean/
ebookmeta.com
https://ebookmeta.com/product/learning-concurrent-programming-in-
scala-second-edition-aleksandar-prokopec-2/
ebookmeta.com
https://ebookmeta.com/product/learning-concurrent-programming-in-
scala-second-edition-aleksandar-prokopec/
ebookmeta.com
https://ebookmeta.com/product/below-zero-the-steminist-novellas-3-1st-
edition-ali-hazelwood/
ebookmeta.com
Caged an Omegaverse Reverse Harem Romance Golden Cage
Omegas Book 1 1st Edition Mona Black
https://ebookmeta.com/product/caged-an-omegaverse-reverse-harem-
romance-golden-cage-omegas-book-1-1st-edition-mona-black/
ebookmeta.com
https://ebookmeta.com/product/the-lost-dragon-dan-michaelson-d-k-
holmberg/
ebookmeta.com
https://ebookmeta.com/product/blueprint-how-dna-makes-us-who-we-are-
with-a-new-afterword-for-the-paperback-edition-robert-plomin/
ebookmeta.com
https://ebookmeta.com/product/mathematical-methods-in-image-
processing-and-inverse-problems-1st-edition-xue-cheng-tai/
ebookmeta.com
https://ebookmeta.com/product/we-are-not-broken-1st-edition-nadine-
little/
ebookmeta.com
Atlas of Emergency Medicine Procedures 2nd Edition Latha
Ganti
https://ebookmeta.com/product/atlas-of-emergency-medicine-
procedures-2nd-edition-latha-ganti/
ebookmeta.com
Functional Programming in Scala, Second Edition
MEAP V08
1. MEAP_VERSION_8
2. Welcome
3. 1_What_is_functional_programming?
4. 2_Getting_started_with_functional_programming_in_Scala
5. 3_Functional_data_structures
6. 4_Handling_errors_without_exceptions
7. 5_Strictness_and_laziness
8. 6_Purely_functional_state
9. 7_Purely_functional_parallelism
10. 8_Property-based_testing
11. 9_Parser_combinators
12. 10_Monoids
13. 11_Monads
14. 12_Applicative_and_traversable_functors
15. 13_External_effects_and_I/O
16. 14_Local_effects_and_mutable_state
17. 15_Stream_processing_and_incremental_I/O
MEAP VERSION 8
Welcome
Thank you for purchasing the MEAP for Functional Programming in Scala,
Second Edition.
The first edition was published in 2014 and quickly became regarded as a
classic text in functional programming. It's been used by university courses
and by study groups, by hobbyists and the by world's largest companies, and
has been translated to different languages. The first edition also had a
reputation for being very difficult, with many readers getting stuck on some
of the exercises.
A lot has changed in Scala since 2014. At the time of publication, Scala 2.10
had been recently released and the Scala FP ecosystem was in its infancy.
Major open source projects like Doobie (http://github.com/tpolecat/doobie)
and http4s (http://http4s.org) were just getting started, the Cats
(http://typelevel.org/cats/) library didn't yet exist, and FS2
(https://github.com/typelevel/fs2), which grew out of the code presented in
chapter 15, was just published. Interoperability between libraries was
cumbersome and the Scala language had some key limitations that made FP
less accessible than it could be.
The second edition of Functional Programming in Scala does not stray far
from the first edition. We cover the same topics and in the same style,
avoiding teaching any specific library and instead focusing on teaching the
underlying concepts that power libraries like Cats, Doobie, http4s, and FS2.
The text has been updated for the release of Scala 3, as well as other changes
that have occurred in the standard library since the original publication using
Scala 2.10. Perhaps controversially, we've decided to include inline,
annotated answers to the exercises. We hope that by doing so, readers that
were discouraged after getting stuck will instead find the inline answers
illuminating and continue with the text. We encourage all readers to try the
exercises before reading the answers though, as practice with FP concepts is
essential to understanding. The exercises and answers, updated for Scala 3,
are also available on the book's Github repository:
http://github.com/fpinscala/fpinscala on the second-edition branch.
In this book
Modifying a variable
Modifying a data structure in place
Setting a field on an object
Throwing an exception or halting with an error
Printing to the console or reading user input
Reading from or writing to a file
Drawing on the screen
We’ll provide a more precise definition of side effects later in this chapter,
but consider what programming would be like without the ability to do these
things, or with significant restrictions on when and how these actions can
occur. It may be difficult to imagine. How is it even possible to write useful
programs at all? If we can’t reassign variables, how do we write simple
programs like loops? What about working with data that changes, or handling
errors without throwing exceptions? How can we write programs that must
perform I/O, like drawing to the screen or reading from a file?
In this chapter, we’ll look at a simple program with side effects and
demonstrate some of the benefits of FP by removing these side effects. We’ll
also discuss the benefits of FP more generally and define two important
concepts—referential transparency and the substitution model.
class Cafe: #1
def buyCoffee(cc: CreditCard): Coffee = #2
val cup = Coffee() #3
cc.charge(cup.price) #4
cup #5
class CreditCard: #6
def charge(price: Double): Unit = #7
println("charging " + price) #8
class Coffee:
val price: Double = 2.0
val cc = CreditCard() #9
val cafe = Cafe()
val cup = cafe.buyCoffee(cc)
As a result of this side effect, the code is difficult to test. We don’t want our
tests to actually contact the credit card company and charge the card! This
lack of testability is suggesting a design change: arguably, CreditCard
shouldn’t have any knowledge baked into it about how to contact the credit
card company to actually execute a charge, nor should it have knowledge of
how to persist a record of this charge in our internal systems. We can make
the code more modular and testable by letting CreditCard be ignorant of
these concerns and passing a Payments object into buyCoffee.
class Cafe:
def buyCoffee(cc: CreditCard, p: Payments): Coffee =
val cup = Coffee()
p.charge(cc, cup.price)
cup
class CreditCard #1
trait Payments: #2
def charge(cc: CreditCard, price: Double): Unit #3
class SimulatedPayments extends Payments: #4
def charge(cc: CreditCard, price: Double): Unit =
println("charging " + price + " to " + cc)
class Coffee:
val price: Double = 2.0
val cc = CreditCard()
val p = Payments()
val cafe = Cafe()
val cup = cafe.buyCoffee(cc, p)
Separate from the concern of testing, there’s another problem: it’s difficult to
reuse buyCoffee. Suppose a customer, Alice, would like to order 12 cups of
coffee. Ideally we could just reuse buyCoffee for this, perhaps calling it 12
times in a loop. But as it is currently implemented, that will involve
contacting the payment system 12 times, authorizing 12 separate charges to
Alice’s credit card! That adds more processing fees and isn’t good for Alice
or the coffee shop.
The functional solution is to eliminate side effects and have buyCoffee return
the charge as a value in addition to returning the Coffee. The concerns of
processing the charge by sending it off to the credit card company, persisting
a record of it, and so on, will be handled elsewhere. Again, we’ll cover
Scala’s syntax more in later chapters, but here’s what a functional solution
might look like:
class Cafe:
def buyCoffee(cc: CreditCard): (Coffee, Charge) = #1
val cup = new Coffee()
(cup, Charge(cc, cup.price)) #2
Here we’ve separated the concern of creating a charge from the processing or
interpretation of that charge. The buyCoffee function now returns a Charge
as a value along with the Coffee. We’ll see shortly how this lets us reuse it
more easily to purchase multiple coffees with a single transaction. But what
is Charge? It’s a data type we just invented containing a CreditCard and an
amount, equipped with a handy function, combine, for combining charges
with the same CreditCard:
case class Charge(cc: CreditCard, amount: Double): #1
def combine(other: Charge): Charge =
if cc == other.cc then #2
Charge(cc, amount + other.amount) #3
else
throw new Exception("Can't combine charges with different cards") #4
class Cafe:
Making Charge into a first-class value has other benefits we might not have
anticipated: we can more easily assemble business logic for working with
these charges. For instance, Alice may bring her laptop to the coffee shop and
work there for a few hours, making occasional purchases. It might be nice if
the coffee shop could combine these purchases Alice makes into a single
charge, again saving on credit card processing fees. Since Charge is first-
class, we can write the following function to coalesce any same-card charges
in a List[Charge]:
def coalesce(charges: List[Charge]): List[Charge] =
charges.groupBy(_.cc).values.map(_.reduce(_.combine(_))).toList
We’re passing functions as values to the groupBy, map, and reduce methods.
You’ll learn to read and write one-liners like this over the next several
chapters. The _.cc and _.combine(_) are syntax for anonymous functions,
which we’ll introduce in the next chapter. As a preview, _.cc is equivalent to
c => c.cc and _.combine(_) is equivalent to (c1, c2) =>
c1.combine(c2).
You may find this kind of code difficult to read because the notation is very
compact. But as you work through this book, reading and writing Scala code
like this will become second nature to you very quickly. This function takes a
list of charges, groups them by the credit card used, and then combines them
into a single charge per card. It’s perfectly reusable and testable without any
additional mock objects or interfaces. Imagine trying to implement the same
logic with our first implementation of buyCoffee!
This is just a taste of why functional programming has the benefits claimed,
and this example is intentionally simple. If the series of refactorings used
here seems natural, obvious, unremarkable, or standard practice, that’s good.
FP is merely a discipline that takes what many consider a good idea to its
logical endpoint, applying the discipline even in situations where its
applicability is less obvious. As you’ll learn over the course of this book, the
consequences of consistently following the discipline of FP are profound and
the benefits enormous. FP is a truly radical shift in how programs are
organized at every level—from the simplest of loops to high-level program
architecture. The style that emerges is quite different, but it’s a beautiful and
cohesive approach to programming that we hope you come to appreciate.
We saw in the case of buyCoffee how we could separate the creation of the
Charge from the interpretation or processing of that Charge. In general, we’ll
learn how this sort of transformation can be applied to any function with side
effects to push these effects to the outer layers of the program. Functional
programmers often speak of implementing programs with a pure core
and a thin layer on the outside that handles effects.
But even so, surely at some point we must actually have an effect on the
world and submit the Charge for processing by some external system. And
aren’t there other useful programs that necessitate side effects or mutation?
How do we write such programs? As we work through this book, we’ll
Other documents randomly have
different content
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.
• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
1.F.4. Except for the limited right of replacement or refund set forth in
paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.