Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no "Functor" trait in Scala? [closed]

In Scala, the generic classes such as Future, Option and List all have methods map and flatMap. As I understand, all of them are like Functors in Haskell.

I was just wondering why there isn't a trait (interface) called Functor in Scala..

Does anyone have ideas about this?

like image 404
Hanfei Sun Avatar asked May 17 '15 15:05

Hanfei Sun


1 Answers

How would such trait look like? Remember, functor is determined by an fmap function which lifts a regular function to a function acting on "functorial" values (or, alternatively, applies a regular function to functor contents). The closest I can think of is

trait Functor[T] {
  type Self[U] <: Functor[U]
  def fmap[U](f: T => U): Self[U]
}

Such definition is not really useful and relatively complex. Traits do not have necessary flexibility for abstracting higher-kinded concepts like functors.

However, Scala does have type classes, that is, it is possible to use traits and implicit parameters in a clever way to implement the type class pattern:

trait Functor[F[_]] {
  def fmap[T, U](f: T => U)(v: F[T]): F[U]
}

implicit object OptionFunctor extends Functor[Option] {
  def fmap[T, U](f: T => U)(v: Option[T]): Option[U] = v match {
    case Some(r) => Some(f(r))
    case None => None
  }
}

def doSomething[F[_]: Functor](f1: F[Int], f2: F[String]): F[Long] = ???  // whatever
// equivalent to:
// doSomething :: Functor f => f Int -> f String -> f Long
// in Haskell

And that's precisely what scalaz provides.

As for why this is not present in the standard library - I don't know. Maybe the type class pattern was not discovered immediately, and the library had already been formed at that moment. Maybe it's just because these are somewhat advanced concepts which don't really belong to the standard library. Maybe something else.

like image 195
Vladimir Matveev Avatar answered Sep 19 '22 23:09

Vladimir Matveev