liveBook · Manning

For-comprehension

As explained in Functional Programming in Scala, Second Edition

A for-comprehension is Scala syntax for expressing a sequence of bindings and a result that the compiler translates into map and flatMap calls.

A for-comprehension expresses a sequence of bindings followed by a yield. Scala translates the bindings into flatMap calls and the final binding and yield into map, making the construct a syntax convenience rather than a new operation. section 4.3.2

Rewriting map2

The explicit form a.flatMap(aa => b.map(bb => f(aa, bb))) can be written as: for aa <- a bb <- b yield f(aa, bb) Both forms combine two Option values and apply f only through the composition provided by map and flatMap. section 4.3.2

def map2[A, B, C](a: Option[A], b: Option[B])(f: (A, B) => C): Option[C] =
  for
    aa <- a
    bb <- b
  yield f(aa, bb)

Compare the for-comprehension directly with its equivalent map and flatMap implementation. section 4.3.2

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines bindings, yield, and compiler desugaring, but stops short of broader implementation details.
Examples
Uses an Option-based map2 implementation with two bindings and a final yield.
What it assumes
Builds from existing map and flatMap operations rather than requiring a separate computation model.
What you can do after
Apply for-comprehensions in place of explicit map and flatMap calls, or expand them to inspect their meaning.
How it connects
Connects for-comprehensions to Option, map, flatMap, and map2.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.