concept flatmap in category functional programming

appears as: flatMaps, flatMap, flatMap, flatMaps
Functional Programming with Kotlin

This is an excerpt from Manning's book Functional Programming with Kotlin.

Write a function flatMap that works like map except that the function given will return a list instead of a single result, and that list should be inserted into the final resulting list. Here is its signature:

Figure 4.3. Flatten and transform the content of Option<Option>> with flatMap
Mapping over the Option type

Write a function flatMap that works like map except that the function given will return a list instead of a single result, and that list should be inserted into the final resulting list. Here is its signature:

We also know from exercise 11.12 that join is a flatMap combined with an identity function:

flatMap(join(y)) { it } ==
    flatMap(y) { join(it) }

join(join(y)) ==
    flatMap(y) { join(it) }

We have also learned in exercise 11.3 that flatMap can be expressed as a map and join, this eliminating the final flatMap.

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.

We can use filter to convert successes into failures if the successful values don’t match the given predicate. A common pattern is to transform an Option via calls to map, flatMap, and/or filter, and then use getOrElse to do error handling at the end:

In the previous chapter on monads, we saw how a lot of the functions we’ve been writing for different combinator libraries can be expressed in terms of a single interface, Monad. Monads provide a powerful interface, as evidenced by the fact that we can use flatMap to essentially write imperative programs in a purely functional way.

The first example we’ll look at is (possibly infinite) streams. We can define map2 and unit for these streams, but not flatMap:

Now consider what happens in a sequence of flatMap calls like the following, where each of the functions validName, validBirthdate, and validPhone has type Either[String, T] for a given type T:

validName(field1) flatMap (f1 =>
validBirthdate(field2) flatMap (f2 =>
validPhone(field3) map (f3 => WebForm(f1, f2, f3))

If validName fails with an error, then validBirthdate and validPhone won’t even run. The computation with flatMap inherently establishes a linear chain of dependencies. The variable f1 will never be bound to anything unless validName succeeds.