One of the biggest advantages of concepts such as functions is the presence of common constructs that allow you to create more complex types from simpler functors and ensure that these complex types have certain properties. The functors understandable seem rather pointless when you consider them in isolation, as you did, but they become more and more useful, the more such constructions you learn and master.
One simple example is that several ways to combine functors also give a functor; for example, if List[A] and Option[A] are functors, that is:
- The composition of the functors:
List[Option[A]] and Option[List[A]] - Functor Products:
(List[A], Option[A]) - Sum of Functors:
Either[List[A], Option[A]]
I don’t know enough to write this in Scala, but in Haskell, facts like these translate into common code like these examples:
-- A generic type to represent the composition of any two functors -- `f` and `g`. newtype Compose fga = Compose { getCompose :: f (ga) } -- If `f` and `g` are functors, so is `Compose fg`. instance (Functor f, Functor g) => Functor (Compose fg) where fmap f (Compose fga) = Compose (fmap (fmap f) fga)
This is a very simple example, but:
- It is already useful, at least as an analytical tool. Many types of data that people write in practice when you look at them through the lens of this example turn out to be products, amounts, or compositions of simpler functors. Therefore, when you understand these constructions, you can automatically “feel” when you write a complex type, which is a functor, and how to write its
map() operation. - More complex examples have the same taste:
- We have a general construction that guarantees certain contracts when creating an instance with a type that implements
Functor ; - When we add a
Functor implementation to any type, we get the opportunity to use this type in this construct.
A more complex example is free monads (the link has an extended Scala example), a general interpreter construct that relies on a custom Functor to define “instructions” for the language. Other links (and this is mostly straight from Google search):
source share