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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With