Is Scala's Option
both a monad and a functor?
As I understand it, functor is just a data type that exposes the following API:
Functor:
wrap (or apply
) which takes a primitive and wraps it inside the functor
map
which takes a functor, unwraps it, applies some function and re-wraps it
So Option
is a functor. Because I can apply an Option
to a primitive giving me Option[T]
. I can also map
on Option
to obtain what's inside the functor and repackage inside Option
.
How is monad different? I had thought that a monad also had an apply
function and a map
function. From this article I gather that a monad also has flatMap
? Which is defined as simply map
but without repackaging the result inside a monad? (Or is it map
without repacking the result inside a functor?!)
Since Option
supplies both map
and flatMap
does that mean that Option
is both a functor and a monad?
Short answer: Yes.
Longer answer: Every monad is an applicative functor and every applicative functor is a functor. In Object-Oriented terms: Monad <: Applicative <: Functor.