Skip to Content
Mastering Functional Programming
book

Mastering Functional Programming

by Anatolii Kmetiuk
August 2018
Intermediate to advanced
380 pages
10h 2m
English
Packt Publishing
Content preview from Mastering Functional Programming

Introducing the flatMap function

Another example of a function that encapsulates a pattern of functional programming is flatMap. Imagine we need to create a function that computes the following mathematical expression: (2 / x) / y + 3. Let's try to do this with the division function that we defined previously:

def f2Match(x: Double, y: Double): Try[Double] =  divide(2, x) match {    case Success(r1) => divide(r1, y) match {      case Success(r2) => Success(r2 + 3)      case f@Failure(_) => f    }    case f@Failure(_) => f  }

The code becomes spaghetti-like here. First, we analyze the result of dividing 2 by x. If successful, we would divide it by y. Then we analyze the result of that division, and if there was no error, we add 3 to the result.

Here, we can no ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Functional Programming

Learning Functional Programming

Jack Widman

Publisher Resources

ISBN: 9781788620796Supplemental Content