I am reading "Programming in Scala 2nd Edition" and I have some idea about monad from a Haskell course I took. However, I do not understand why the following code "magically" works:
scala> val a: Option[Int] = Some(100)
a: Option[Int] = Some(100)
scala> val b = List(1, 2, 3)
b: List[Int] = List(1, 2, 3)
for ( y <- b; x <- a ) yield x;
res5: List[Int] = List(100, 100, 100)
I do not understand the above because according to the book's Chapter 23.4, the for
expression is translated to something like:
b flatMap ( y =>
a map ( x => x )
)
I am puzzled why the above code compiles because y => a map (x => x)
is of type Int => Option[Int]
, while the b.flatMap
expects a Int => List[Something]
.
On the other hand, the following code does NOT compile (which is good otherwise I would be more lost):
scala> for ( x <- a; y <- b ) yield y;
<console>:10: error: type mismatch;
found : List[Int]
required: Option[?]
for ( x <- a; y <- b ) yield y;
^
So what is magical with the first example?