Applicative's Interchange Law

[亡魂溺海] 提交于 2020-07-09 04:11:15

问题


Applicative Programming with Effects, the paper from McBride and Paterson, presents the interchange law:

u <*> pure x = pure (\f -> f x) <*> u

In order to try to understand it, I attempted the following example - to represent the left-hand side.

ghci> Just (+10) <*> pure 5
Just 15

How could I write this example using the right-hand side?

Also, if u is an f (a -> b) where f is an Applicative, then what's the function on the right-hand side: pure (\f -> f x) ...?


回答1:


It would be written as

pure (\f -> f 5) <*> Just (+10)

Or even

pure ($ 5) <*> Just (+10)

Both are equivalent in this case. Quite literally, you're wrapping a function with pure that takes another function as its argument, then applies x to it. You provide f as the contents of the Just, which in this case is (+10). When you see the lambda syntax of (\f -> f x), it's being very literal, this is a lambda used for this definition.




回答2:


The point this law makes is about preservation of exponential by the Applicative Functor: what is a exponential in the origin, is also an exponential in the image of the category.

Please, observe that the actual action of the Applicative Functor is the transformation of the following kind: strength :: (f a, f b) -> f (a, b); then ap or <*> is just fmap eval over the result, or, written fully, ap = curry $ fmap (uncurry ($)) . strength.

This law then says that since in the origin g $ x == ($ x) $ g, lifting ($), x and ($ x) should preserve the equality. Notice, that "normal" Functors will only preserve the equality only if g is lifted, too, but Applicative Functors will preserve this equality for any object of type f (a->b) in place of g. This way the whole type f (a->b) behaves like f a -> f b, whereas for "normal" Functors it only needs to behave like f a -> f b for images of the arrows in the origin (to make the diagrams commute and fulfill the promises of the Functor).

As to representing the right-hand-side of the law, you've already been advised to take it literally, pure ($ 5) <*> Just (+10)



来源:https://stackoverflow.com/questions/27285918/applicatives-interchange-law

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!