Skip to Content
Mastering Functional Programming
book

Mastering Functional Programming

by Anatolii Kmetiuk
August 2018
Intermediate to advanced
380 pages
10h 2m
English
Packt Publishing
Content preview from Mastering Functional Programming

Implementation of the type class

Let's take a look at how the type class can be implemented for a data type. For example, let's look at Either:

implicit val applicative: Applicative[Fx] = new Applicative[Fx] {  override def ap[A, B](ff: Fx[A => B])(fa: Fx[A]): Fx[B] = (ff, fa)  match {    case (Right(f), Right(a)) => Right(f(a))    case (Left(e1), Left(e2)) => Left(e1 ++ e2)    case (Left(e), _) => Left(e)    case (_, Left(e)) => Left(e)  }  override def pure[A](a: A): Fx[A] = Right(a)}

You can see how the type class can be implemented for Either with Left being List[String]. So, as you can see, if two computations are successful, that is, they are Right, we simply combine them. However, if at least one of them is Left, we combine the Left side of both computations ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Functional Programming

Learning Functional Programming

Jack Widman

Publisher Resources

ISBN: 9781788620796Supplemental Content