Type projection example from "Scala in Action" (chapter 8)
could anyone help me with below code bits from the book?
trait Mapper[F[_]] {
def fmap[A, B](xs: F[A], f: A => B): F[B]
}
def VectorMapper = new Mapper[Vector] {
def fmap[A, B](xs: Vector[A], f: A => B): Vector[B] = xs map f
}
That was simple: trait definition using higher-kinded type F[_] for usage
with any "container-like" types, then a concrete mapper for Vector.
Then goes a tricky part. Mapper for Either. I understand {type E[A] =
Either[X, A]} just as a block of code, and ({type E[A] = Either[X, A]})#E
as a projection that takes that type alias E and by that "hides" the
presence of X.
def EitherMapper[X] = new Mapper[({type E[A] = Either[X, A]})#E ] {
def fmap[A, B](r: Either[X, A], f: A => B): Either[X, B] = r match {
case Left(a) => Left(a)
case Right(a) => Right(f(a))
}
}
Questions:
Why do we need X in the def EitherMapper[X] = part?
Why author tries to "hide" presence of X (i.e. Left) by use of projection,
and does not simply specify = new Mapper[Either[X, A]]?
Thanks for details.
No comments:
Post a Comment