We know that any generic type F[_]
withmap
method, which complies to some laws, is a functor. For instance, List[_]
, Option
One of the biggest benefits of concepts like functions is that there are generic constructions that allow you to build more complex types out of simpler functors, and guarantee that these complex types have certain properties. Functors understandably seem rather pointless when you consider them in isolation as you have done, but they become more and more useful the more such constructions you learn and master.
One of the simpler examples is that several ways of combining functors also yield a functor; e.g., if List[A]
and Option[A]
are functors, so are:
List[Option[A]]
and Option[List[A]]
(List[A], Option[A])
Either[List[A], Option[A]]
I don't know enough to write this out in Scala, but in Haskell facts like these translate into generic code like these examples:
-- A generic type to represent the composition of any two functors
-- `f` and `g`.
newtype Compose f g a = Compose { getCompose :: f (g a) }
-- If `f` and `g` are functors, so is `Compose f g`.
instance (Functor f, Functor g) => Functor (Compose f g) where
fmap f (Compose fga) = Compose (fmap (fmap f) fga)
This is a very simple example, but:
map()
operation.Functor
;Functor
implementation to any a type, we gain the ability to use that type in that construction.A more elaborate example is free monads (link has an extended Scala example), a generic interpreter construction that relies on user-supplied Functor
s to define the "instructions" for the language. Other links (and these are mostly straight from a Google search):