I have been working through the great good book, but I am struggling slightly with Applicative Functors.
In the following example max
is applied to the contents of the two Maybe functors and returns Just 6
.
max <$> Just 3 <*> Just 6
Why in the following example is Left "Hello"
returned instead of the contents of the Either functors: Left "Hello World"
?
(++) <$> Left "Hello" <*> Left " World"
Like monads, applicative functors are functors with extra laws and operations; in fact, Applicative is an intermediate class between Functor and Monad .
Every Monad is an Applicative Just as IO , every monad can be made into an applicative functor.
A functor is a data type that implements the Functor typeclass. An applicative is a data type that implements the Applicative typeclass. A monad is a data type that implements the Monad typeclass. A Maybe implements all three, so it is a functor, an applicative, and a monad.
Functor in Haskell is a typeclass that provides two methods – fmap and (<$) – for structure-preserving transformations. To implement a Functor instance for a data type, you need to provide a type-specific implementation of fmap – the function we already covered.
It's because the type parameter in the Functor
instance (and Applicative
etc.) is the second type parameter. In
Either a b
the a
type, and the Left
values are not affected by functorial or applicative operations, because they are considered failure cases or otherwise inaccessible.
instance Functor (Either a) where
fmap _ (Left x) = Left x
fmap f (Right y) = Right (f y)
Use Right
,
(++) <$> Right "Hello" <*> Right " World"
to get concatenation.
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