concept map2 in category functional programming

This is an excerpt from Manning's book Functional Programming with Kotlin.
In the implementation found in Listing 4.8,
map2is only able to report one error, even if both the name and the age are invalid. What would you need to change in order to report both errors? Would you changemap2or the signature ofmkPerson? Or could you create a new data type that captures this requirement better thanEitherdoes, with some additional structure? How wouldorElse,traverse, andsequencebehave differently for that data type?
The higher-order function
map2is a new function for combining the result of two parallel computations. What is its signature? Give the most general signature possible (don’t assume it works only forInt).
What about
map2—should it take its arguments lazily? Would it make sense formap2to run both sides of the computation in parallel giving each side equal opportunity to run? It would seem arbitrary for the order of themap2arguments to matter as we simply want it to indicate that the two computations being combined are independent and can be run in parallel. What choice lets us implement this meaning? As a simple example, consider what happens ifmap2is strict in both arguments as we evaulatesum(listOf(1, 2, 3, 4)). Take a minute to work through and understand the following (somewhat stylized) program trace.Listing 7.5. Strict evaluation of both parameters results in left side being evaluated first
sum(listOf(1, 2, 3, 4)) #1 map2( sum(listOf(1, 2)), sum(listOf(3, 4)) ) { i: Int, j: Int -> i + j } #2 map2( map2( sum(listOf(1)), sum(listOf(2)) ) { i: Int, j: Int -> i + j }, #3 sum(listOf(3, 4)) ) { i: Int, j: Int -> i + j } map2( map2( unit { 1 }, unit { 2 } ) { i: Int, j: Int -> i + j }, #4 sum(listOf(3, 4)) ) { i: Int, j: Int -> i + j } map2( map2( unit { 1 }, unit { 2 } ) { i: Int, j: Int -> i + j }, map2( sum(listOf(3)), sum(listOf(4)) ) { i: Int, j: Int -> i + j } #5 ) { i: Int, j: Int -> i + j }To evaluate
sum(x)in Listing 7.4, we substitutexinto the definition ofsum, as we’ve done in previous chapters. Becausemap2is strict, and Kotlin evaluates arguments left to right, whenever we encountermap2(sum(x),sum(y)) { i, j -> i + j }, we then have to evaluatesum(x)and so on recursively. This has the unfortunate consequence that we’ll strictly construct the entire left half of the tree of summations first before moving on to (strictly) constructing the right half. Heresum(listOf(1,2))gets fully expanded before we considersum(listOf(3,4)). And ifmap2evaluates its arguments in parallel (using whatever resource is being used to implement the parallelism, like a thread pool), that implies the left half of our computation will start executing before we even begin constructing the right half of our computation.What if we keep
map2strict, but don’t let it begin execution immediately? Does this help? Ifmap2doesn’t begin evaluation immediately, this implies aParvalue is merely constructing a description of what needs to be computed in parallel. Nothing actually occurs until we evaluate this description, perhaps by using aget-like function. The problem is that if we construct our descriptions strictly, they’ll be rather heavyweight objects. Looking at the trace in Listing 7.5, our description will have to contain the full tree of operations to be performed.Listing 7.6. Strict construction of the description results in a full tree of operations
map2( map2( unit { 1 }, unit { 2 }) { i: Int, j: Int -> i + j }, map2( unit { 3 }, unit { 4 }) { i: Int, j: Int -> i + j } ) { i: Int, j: Int -> i + j }Whatever data structure we use to store this description, it’ll likely occupy more space than the original list itself! It would be nice if our descriptions were more lightweight. It also seems that we should make
map2lazy and have it begin immediate execution of both sides in parallel. This also addresses the problem of giving either side priority over the other.

This is an excerpt from Manning's book Functional Programming in Scala.
With map2, we can now implement parseInsuranceRateQuote:
def parseInsuranceRateQuote( age: String, numberOfSpeedingTickets: String): Option[Double] = { val optAge: Option[Int] = Try { age.toInt } #1 val optTickets: Option[Int] = Try { numberOfSpeedingTickets.toInt } map2(optAge, optTickes)(insuranceRateQuote) #2 } #1: Functions accepting a single argument may be called with braces instead of parentheses; this is equivalent to Try(age.toInt). #2: If either parse fails, this will immediately return None.The map2 function means that we never need to modify any existing functions of two arguments to make them “Option-aware.” We can lift them to operate in the context of Option after the fact. Can you already see how you might define map3, map4, and map5? Let’s look at a few other similar cases.
Here, the implementation of traverse is using map2 and unit, and we’ve seen that map2 can be implemented in terms of flatMap:
def map2[A,B,C](ma: F[A], mb: F[B])(f: (A,B) => C): F[C] = flatMap(ma)(a => map(mb)(b => f(a,b)))What you may not have noticed is that a large number of the useful combinators on Monad can be defined using only unit and map2. The traverse combinator is one example—it doesn’t call flatMap directly and is therefore agnostic to whether map2 is primitive or derived. Furthermore, for many data types, map2 can be implemented directly, without using flatMap.
All this suggests a variation on Monad—the Monad interface has flatMap and unit as primitives, and derives map2, but we can obtain a different abstraction by letting unit and map2 be the primitives. We’ll see that this new abstraction, called an applicative functor, is less powerful than a monad, but we’ll also see that limitations come with benefits.
Applicative functors can be captured by a new interface, Applicative, in which map2 and unit are primitives.
Listing 12.1. Creating the Applicative interface
trait Applicative[F[_]] extends Functor[F] { // primitive combinators def map2[A,B,C](fa: F[A], fb: F[B])(f: (A, B) => C): F[C] def unit[A](a: => A): F[A] // derived combinators def map[B](fa: F[A])(f: A => B): F[B] = #1 map2(fa, unit(()))((a, _) => f(a)) #2 def traverse[A,B](as: List[A])(f: A => F[B]): F[List[B]] #3 as.foldRight(unit(List[B]()))((a, fbs) => map2(f(a), fbs)(_ :: _)) } #1: We can implement map in terms of unit and map2. #2: Recall () is the sole value of type Unit, so unit(()) is calling unit with the dummy value (). #3: Definition of traverse is identical.This establishes that all applicatives are functors. We implement map in terms of map2 and unit, as we’ve done before for particular data types. The implementation is suggestive of laws for Applicative that we’ll examine later, since we expect this implementation of map to preserve structure as dictated by the Functor laws.