Functor in scala isn't quite the same thing as what they call that in C++. It is a category with an operation like
def map[A, B](fa: F[A])(f: A => B): F[B]
that turns F[A]
into F[B]
given a transformer from A
to B
.
For example, an Option
is a functor, that applies the transformation to the inner value when it is defined. A List
is a functor, that applies the transformer to each element, etc.
Now, consider, something like Either[A, B]
. Suppose, we wanted to define a functor for that. It takes two type parameters, but Functor
only has one, so we have to choose on which the Functor
will operate. It is common to use Either
in a way, where Right
is the default case, and Left
is an exception (an error condition). So, it is natural, to consider it right-biased:
def eitherFunctor[T] = new Functor[Either[T, ?]] {
def map(fa: Either[T, A])(f: A => B): Either[T, B] = fa match {
case Right(a) => Right(f(a))
case Left(t) => Left(t)
}
}
This works kinda like Option.map
: when Either
is a Right
, it applies the transformer, otherwise, just returns the Left
untouched. Thus, it can be said that Either
is a right-biased functor, because it only operates on its right side.