Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of `pure` in Applicative Functor

Meet the Applicative typeclass. It lies in the Control.Applicative module and it defines two methods, pure and <*>. It doesn't provide a default implementation for any of them, so we have to define them both if we want something to be an applicative functor.

I am trying to understand who is using pure function. I do use (<*>) function for which applicative functors are most useful for. But I am not sure who really uses pure.

I read something like pure (+3) <*> Just 10 but it can be written as Just (+3) <*> Just 10 too.

Above is just one confusion of too many I have. What is the true purpose of defining pure and when do I get to use it (or) who is already using it?

like image 683
Sumanth Kumar Mora Avatar asked Jul 25 '18 06:07

Sumanth Kumar Mora


People also ask

What does pure do in Haskell?

A function is called pure if it corresponds to a function in the mathematical sense: it associates each possible input value with an output value, and does nothing else.

How many methods should a functor instance have?

According to the implementation, we can map another Functor using two methods: "Pure" and "<*>". The "Pure" method should take a value of any type and it will always return an Applicative Functor of that value.

Why is functor useful?

Functor is also important in its role as a superclass of Applicative and of Traversable . When working with these more powerful abstractions, it's often very useful to reach for the fmap method. Show activity on this post. For example, it's possible to derive the function lift in a way that works for any functor.

Could you comfortably explain the difference between a monad and an applicative functor?

Functors apply a function to a wrapped value: Applicatives apply a wrapped function to a wrapped value: Monads apply a function that returns a wrapped value to a wrapped value. Monads have a function >>= (pronounced "bind") to do this.


1 Answers

<*> :: f (a -> b) -> f a -> f b, this operator accepts a function in the applicative type, as well as a value in the applicative type. The first argument of this operator can not thus be simply a function, but it has to be residing within an applicative.

The pure function solves problems that might occur here (e.g wanting to apply a function that is not residing in the applicative). It accepts a function that is not currently residing in the applicative, and lifts it into the applicative.pure :: a -> f a

(+3) :: Int -> Int, and Just 10 :: Maybe Int, you can not thus evaluate (+3) <*> Just 10 as the types do not work; the (+3) has to be promoted to a value in the Maybe applicative.

For Maybe a, the definition of pure is pure = Just, which is why you can write either pure (+3) or Just (+3)

--

I'll leave it to you to look into the <$> operator :-) Remember, every Applicative is a Functor.

like image 81
Robert Avatar answered Sep 18 '22 16:09

Robert