Chapter 8

  1. Implement Functor[Try].
implicit val tryFunctor: Functor[Try] = new Functor[Try] {
override def map[A, B](in: Try[A])(f: A => B): Try[B] = in.map(f)
override def mapC[A, B](f: A => B): Try[A] => Try[B] = fa => map(fa)(f)
}

 

  1. Implement Applicative[Try].
implicit val tryApplicative: Applicative[Try] = new Applicative[Try] {
override def apply[A, B](a: Try[A])(f: Try[A => B]): Try[B] = (a, f) match {
case (Success(a), Success(f)) => Try(f(a))
case (Failure(ex), _) => Failure(ex)
case (_, Failure(ex)) => Failure(ex)
}
override def unit[A](a: => A): Try[A] = Success(a)
}

 

  1. Implement  Applicative[Either].
implicit def eitherApplicative[L] = new Applicative[({ type T[A] = Either[L, A] })#T] {
override def apply[A, B](a: Either[L, A])(f: Either[L, A => B]): Either[L, B] = (a, f) match {
case (Right(a), Right(f)) => Right(f(a))
case (Left(l), _) => Left(l)
case (_, Left(l)) => Left(l)
}
override def unit[A](a: => A): Either[L, A] = Right(a)
}

 

  1. Implement Traversable[Try].
implicit val tryTraversable = new Traversable[Try] {
override def map[A, B](in: Try[A])(f: A => B): Try[B] = Functor.tryFunctor.map(in)(f)
override def traverse[A, B, G[_] : Applicative](a: Try[A])(f: A => G[B]): G[Try[B]] = {
val G = implicitly[Applicative[G]]
a match {
case Success(s) => G.map(f(s))(Success.apply)
case Failure(ex) => G.unit(Failure(ex)) // re-wrap the ex to change the type of Failure
}
}
}
  1. Implement Traversable[Either].
implicit def eitherTraversable[L] = new Traversable[({ type T[A] = Either[L, A] })#T] {
override def map[A, B](in: Either[L, A])(f: A => B): Either[L, B] =
Functor.eitherFunctor[L].map(in)(f)
override def traverse[A, B, G[_] : Applicative](a: Either[L, A])(f: A => G[B]): G[Either[L, B]] = {
val G = implicitly[Applicative[G]]
a match {
case Right(s) => G.map(f(s))(Right.apply)
case Left(l) => G.unit(Left(l)) // re-wrap the l to change the type of Failure
}
}
}
  1. Implement Traversable.compose.
trait Traversable[F[_]] extends Functor[F] {
def traverse[A,B,G[_]: Applicative](a: F[A])(f: A => G[B]): G[F[B]]
def sequence[A,G[_]: Applicative](a: F[G[A]]): G[F[A]] = traverse(a)(identity)

def compose[H[_]](implicit H: Traversable[H]): Traversable[({type f[x] = F[H[x]]})#f] = {
val F = this
new Traversable[({type f[x] = F[H[x]]})#f] {
override def traverse[A, B, G[_] : Applicative](fa: F[H[A]])(f: A => G[B]) =
F.traverse(fa)((ga: H[A]) => H.traverse(ga)(f))

override def map[A, B](in: F[H[A]])(f: A => B): F[H[B]] =
F.map(in)((ga: H[A]) => H.map(ga)(f))
}
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.28.179