concept flatMap in category scala

appears as: flatMap, The flatMap, flatMap
Get Programming with Scala MEAP V07

This is an excerpt from Manning's book Get Programming with Scala MEAP V07.

Note that pattern matching is not the only way to handle an optional value: in the next lesson, I’ll show you how you can achieve the same using predefined higher order functions such as map and flatMap.

Figure 23.2: Visual representation of the flatMap operation on Option. If the value is present, flatMap will apply the function f to it, which will produce a new optional value. If the optional value is absent, it will return None without applying any function f.

In the previous lesson, you have learned the basics of the type List of the Scala Standard Collection library. In this lesson, you are going to learn about the basic operations you can perform on lists: they are similar to their corresponding equivalent for the class Option. You will see how to use the map operation to apply a function to the elements of a sequence. You are going to discover how to unify nested lists using flatten, and how to chain them together using flatMap. You are also going to learn how to use a for-comprehension statement to combine and manipulate multiple lists into one. In the capstone, you will use the operations to extract information from the Movies Dataset.

The flatMap function combines the map and flatten operations. You can re-implement your getNumbers method from listing 28.4 as follows:

Listing 28.5: Getting all the contact numbers with flatMap
def getNumbers(contacts: List[Contact]): List[ContactNumber] =
  contacts.flatMap(_.numbers)

The flatMap function on List[A] is a higher order function that applies a function f of type A => List[B] to produce an instance of List[B]:

Functional Programming in Scala

This is an excerpt from Manning's book Functional Programming in Scala.

flatMap is similar, except that the function we provide to transform the result can itself fail.

As the implementation of variance demonstrates, with flatMap we can construct a computation with multiple stages, any of which may fail, and the computation will abort as soon as the first failure is encountered, since None.flatMap(f) will immediately return None, without running f.

Here we’ve just taken the implementation of map2 and changed Parser, Gen, and Option to the polymorphic F of the Mon[F] interface in the signature.[5] But in this polymorphic context, this won’t compile! We don’t know anything about F here, so we certainly don’t know how to flatMap or map over an F[A].

Listing 11.3. Adding map and flatMap to our trait
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest