[英]What are the applicative functor laws in terms of pure and liftA2?
I'm playing around with formulating Applicative in terms of pure
and liftA2
(so that (<*>) = liftA2 id
becomes a derived combinator). 我正在使用pure
和liftA2
来配制Applicative(因此(<*>) = liftA2 id
成为派生组合子)。
I can think of a bunch of candidate laws, but I'm not sure what the minimal set would be. 我可以想到一堆候选法则,但我不确定最小集合是什么。
f <$> pure x = pure (fx)
f <$> liftA2 gxy = liftA2 ((f .) . g) xy
liftA2 f (pure x) y = fx <$> y
liftA2 fx (pure y) = liftA2 (flip f) (pure y) x
liftA2 f (g <$> x) (h <$> y) = liftA2 (\\xy -> f (gx) (hy)) xy
Based on McBride and Paterson's laws for Monoidal
(section 7) I'd suggest the following laws for liftA2
and pure
. 基于McBride和Paterson的Monoidal
定律 (第7节),我建议对liftA2
和pure
进行以下定律。
left and right identity 左右身份
liftA2 (\_ y -> y) (pure x) fy = fy
liftA2 (\x _ -> x) fx (pure y) = fx
associativity 关联
liftA2 id (liftA2 (\x y z -> f x y z) fx fy) fz =
liftA2 (flip id) fx (liftA2 (\y z x -> f x y z) fy fz)
naturality 自然性
liftA2 (\x y -> o (f x) (g y)) fx fy = liftA2 o (fmap f fx) (fmap g fy)
It isn't immediately apparent that these are sufficient to cover the relationship between fmap
and Applicative
's pure
and liftA2
. 目前尚不清楚这些是否足以涵盖fmap
与Applicative
的pure
和liftA2
之间的关系。 Let's see if we can prove from the above laws that 让我们看看我们是否可以从上述法律证明
fmap f fx = liftA2 id (pure f) fx
We'll start by working on fmap f fx
. 我们将从fmap f fx
。 All of the following are equivalent. 以下所有内容都是等效的。
fmap f fx
liftA2 (\x _ -> x) (fmap f fx) ( pure y ) -- by right identity
liftA2 (\x _ -> x) (fmap f fx) ( id (pure y)) -- id x = x by definition
liftA2 (\x _ -> x) (fmap f fx) (fmap id (pure y)) -- fmap id = id (Functor law)
liftA2 (\x y -> (\x _ -> x) (f x) (id y)) fx (pure y) -- by naturality
liftA2 (\x _ -> f x ) fx (pure y) -- apply constant function
At this point we've written fmap
in terms of liftA2
, pure
and any y
; 在这一点上,我们用liftA2
, pure
和任何y
写了fmap
; fmap
is entirely determined by the above laws. fmap
完全由上述法律决定。 The remainder of the as-yet-unproven proof is left by the irresolute author as an exercise for the determined reader. 尚未经证实的证据的其余部分由犹豫不决的作者留下作为坚定读者的练习。
Per the online book, Learn You A Haskell:Functors, Applicative Functors and Monoids , the Appplicative Functor laws are bellow but reorganized for formatting reasons; 根据在线书籍, 了解你的Haskell:Functors,Applicative Functors和Monoids ,Appplicative Functor法律如下,但由于格式原因进行了重组; however, I am making this post community editable since it would be useful if someone could embed derivations: 但是,我正在使这个帖子社区可编辑,因为如果有人可以嵌入派生将是有用的:
identity] v = pure id <*> v
homomorphism] pure (f x) = pure f <*> pure x
interchange] u <*> pure y = pure ($ y) <*> u
composition] u <*> (v <*> w) = pure (.) <*> u <*> v <*> w
Note: 注意:
function composition] (.) = (a->b) -> (b->c) -> (a->c)
application operator] $ = (a->b) -> a -> b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.