anon
anon

Reputation:

What is the meaning of `pure x = (\_ -> x)`?

I'm reading the instance of Applicative for functions, and encountered a line

instance Applicative ((->) r) where  
  pure x = (\_ -> x)  
  f <*> g = \x -> f x (g x)

I understand the syntax, but don't understand the meaning of the second line.

My understanding is: partially applied function ((->) r) gets a value and wraps that value into the context, which contains function that always returns that value.

Why doesn't it just compute the result by applying partially applied function to that x, and only after that it would store the result in Applicative context?

Upvotes: 2

Views: 296

Answers (1)

Mor A.
Mor A.

Reputation: 4656

The signatures of pure and (<*>) for the function instance are

pure :: a -> ((->) r a)  
(<*>) :: ((->) r (a -> b)) -> ((->) r a) -> ((->) r b)  

Writing the (->) as infix operator gives

pure :: a -> (r -> a)  
(<*>) :: (r -> (a -> b)) -> (r -> a) -> (r -> a)

So pure is a function that takes a parameter of type a and returns a function that takes a parameter of type r and returns a value of type a.
Since we can't know the type of r as we write pure, we can only give a function that return the parameter given to pure.

Upvotes: 8

Related Questions