What should map2
return in the case of List[Int]
?
I’m trying for the 5th time to read the Monad chapter of the Red Book (Functional Programming in Scala by Chiusano and Bjarnason). Section 11.2 attempts to motivate monads by looking at previous implementations of map2
for three classes introduced in previous chapters, Gen
, Parser
, and Option
.
However, the generalization seems weird to me.
def map2[A,B,C](fa:Gen[A], fb:Gen[B], f:(A,B)=>C):Gen[C] = {
fa flatMap (a => fb map (b => f(a,b)))
}
def map2[A,B,C](fa:Parser[A], fb:Parser[B], f:(A,B)=>C):Parser[C] = {
fa flatMap (a => fb map (b => f(a,b)))
}
def map2[A,B,C](fa:Option[A], fb:Option[B], f:(A,B)=>C):Option[C] = {
fa flatMap (a => fb map (b => f(a,b)))
}
Thus in they define map2
more generally as follows:
trait Mon[F[_]] {
def map2[A,B,C](fa: F[A], fb: F[B], f: (A,B)=>C): F[C] =
fa flatMap (a => fb map (b => f(a,b)))
However, when I try to use this definition for List[Int] I get an inconsistent result.
Should map2(List(1,2,3),List(10,20,30), _+_)
return List(11,22,33)
, or should it return List(11, 21, 31, 12, 22, 32, 13, 23, 33)
? I was under the impression map2
was supposed to apply the binary function to corresponding elements of the two lists, not every possible pairing.
Do I misunderstand map2
?