Applicative type class

We would like to define a new primitive for the preceding scenario. We can call this method zip:

type Fx[A] = Either[List[String], A]def zip[A, B](f1: Fx[A], f2: Fx[B]): Fx[(A, B)] = (f1, f2) match {  case (Right(r1), Right(r2)) => Right((r1, r2))  case (Left(e1), Left(e2)) => Left(e1 ++ e2)  case (Left(e), _) => Left(e)  case (_, Left(e)) => Left(e)}

The method will take two computations as its arguments, and it will output a combined result of two of its supplied inputs as a tuple under their common effect type.

Also notice that we are dealing with specific cases of Left being a list of strings. This is to combine multiple error strings for multiple failed computations into one error report.

The way it works is that if ...

Get Mastering Functional Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.