Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applicative Functors and Left from Either

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 image 835
Jim Jeffries Avatar asked Dec 14 '12 12:12

Jim Jeffries


People also ask

Is applicative a functor?

Like monads, applicative functors are functors with extra laws and operations; in fact, Applicative is an intermediate class between Functor and Monad .

Are all monads applicative functors?

Every Monad is an Applicative Just as IO , every monad can be made into an applicative functor.

What are functors Applicatives and monads?

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.

Is functor a Typeclass?

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.


1 Answers

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.

like image 56
Daniel Fischer Avatar answered Sep 23 '22 20:09

Daniel Fischer