I'm having a hard time breaking down the evaluation in Section 6.9 when implementing map2 in terms of FlatMap from Functional Programming in Scala.
So map2 looks like
def map2[A,B,C](ra: Rand[A], rb: Rand[B])(f: (A, B) => C): Rand[C] = {
rng => {
val (a, r1) = ra(rng)
val (b, r2) = rb(r1)
(f(a, b), r2)
}
}
and flatMap looks like:
def flatMap[A, B](f: Rand[A])(g: A => Rand[B]): Rand[B] = rng => {
val (a, r1) = f(rng)
g(a)(r1)
}
I beat my head against a wall for a few days and could not figure out how to do map2 in terms of flatmap (map, oddly, came to me right away).
Looking at a solution to map2 in terms of flatMap from the solutions repo:
def _map2[A,B,C](s1: Rand[A], s2: Rand[B])(f: (A, B) => C): Rand[C] = {
flatMap(s1)(a => flatMap(s2)(b => unit(f(a,b))))
}
But I'm confused on how this function expands in terms of evaluation --I can't seem to write out the evaluation by hand. I don't see how I have the second f: (A, B) => C that gets returned to the outer flatMap.
I suppose this is the next question after this post: Implementation of flatMap() for State transition !