简体   繁体   中英

What is functor bias?

Following up from C++ Functors - and their uses , I have come across 'right biased functor' and 'left biased functor'. I have tried to do some research on my own, but I am still failing to understand the difference between both, and what functor bias even is.

Can someone please give an overview of what functor bias is, the difference between right bias and left bias, along with any examples of how this would be useful? It would be great if Scala could be used for the examples.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM