1

The following for-expression seems intuitive to me. Take each item in List(1), then map over List("a"), and then return a List[(Int, String)].

scala> val x = for {
     | a <- List(1)
     | b <- List("a")
     | } yield (a,b)
x: List[(Int, String)] = List((1,a))

Now, converting it to a flatMap, it seems less clear to me. If I understand correctly, I need to call flatMap first since I'm taking the initial List(1), and then applying a function to convert from A => List[B].

scala> List(1).flatMap(a => List("a").map(b => (a,b) ))
res0: List[(Int, String)] = List((1,a))

After using the flatMap, it seemed necessary to use a map since I needed to go from A => B.

But, as the number of items increases in the for-expression (say 2 to 3 items), how do I know whether to use a map or flatMap when converting from for-expression to flatMap?

Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384
  • possible duplicate of [Getting the desugared part of a Scala for/comprehension expression?](http://stackoverflow.com/questions/9891407/getting-the-desugared-part-of-a-scala-for-comprehension-expression) – drexin Nov 27 '13 at 06:01

1 Answers1

8

In using the for comprehension you always flatMap until the last value that you extract which you map. So if you have three items:

  for {
    a <- List("a")
    b <- List("b")
    c <- List("c")
  } yield (a, b, c)

It would be the same as:

  List("a").flatMap(a => List("b").flatMap(b => List("c").map(c => (a, b, c))))

If you look at the signature of flatMap it's A => M[B]. So as we add elements to the for comprehension we need to flatMap them in since we continue to add M[B] to the comprehension. When we get to the last element, there's nothing left to add so we use map since we just want to go from A => B. Hope that makes sense, if not take you should watch some of the videos in the Reactive Programming class on Coursera as they go over this quite a bit.

Noah
  • 13,821
  • 4
  • 36
  • 45
  • 4
    See also [Daniel Sobral's answer](http://stackoverflow.com/questions/1052476/what-is-scalas-yield/1059501#1059501), which is also found in the Odersky book, and less readably, in the spec. – Ed Staub Nov 27 '13 at 03:36