Haskell 就纯函数和liftA2而言,应用函子定律是什么?
我正在玩弄用Haskell 就纯函数和liftA2而言,应用函子定律是什么?,haskell,applicative,Haskell,Applicative,我正在玩弄用pure和liftA2来表示Applicative(这样()=lifta2id就变成了一个派生的组合词) 我能想到一大堆候选定律,但我不确定最小集是什么 f纯x=纯(f x) f liftA2 g x y=liftA2((f.)g)x y lifta2f(纯x)y=fxy lifta2fx(纯y)=liftA2(翻转f)(纯y)x lifta2f(gx)(hy)=liftA2(\xy->f(gx)(hy))xy 根据麦克布莱德和帕特森(第7节),我建议对liftA2和pure采用以
pure
和liftA2
来表示Applicative(这样()=lifta2id
就变成了一个派生的组合词)
我能想到一大堆候选定律,但我不确定最小集是什么
f纯x=纯(f x)
f liftA2 g x y=liftA2((f.)g)x y
lifta2f(纯x)y=fxy
lifta2fx(纯y)=liftA2(翻转f)(纯y)x
lifta2f(gx)(hy)=liftA2(\xy->f(gx)(hy))xy
根据麦克布莱德和帕特森(第7节),我建议对
liftA2
和pure
采用以下法律
左右标识
关联性
自然性
目前还不清楚这些是否足以涵盖fmap
和Applicative
的pure
和liftA2
之间的关系。让我们看看能否从上述定律中证明
fmap f fx = liftA2 id (pure f) fx
我们将从fmap f fx
开始。以下所有内容都是等效的
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
在这一点上,我们已经用liftA2
、pure
和anyy
编写了fmap
<代码>fmap完全由上述法律决定。犹豫不决的作者将尚未证实的证据的剩余部分留给坚定的读者作为练习。根据在线书籍,应用函子定律如下,但由于格式原因重新组织;但是,我正在使此帖子社区可编辑,因为如果有人可以嵌入派生,它将非常有用:
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
liftA2
是用和来定义的,我不知道你为什么要用liftA2
来定义
。是的,但是我想做一些类似于EZ Yang在他的文章中比较应用性和单项式的事情:Applicative
与pure
和liftA2
与这个类相同,它有一个法律列表。使用pure
和liftA2
从Monoidal
到Applicative
。@Cirdec,整洁。很容易读懂pure
和liftA2
的相应定律吗?有趣的是,身份法则可以这样重写:liftA2常量fx(pure y)==const fx(pure y y)
和flip(liftA2(flip const))fx(pure y y)==const fx(pure y)
(或liftA2(flip const)(pure x)fy==flip const(纯x)fy
),这可能会增加一个有趣的角度。()
应该不是(a->b)->(b->c)->(a->c)
?
fmap f fx = liftA2 id (pure f) fx
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
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
function composition] (.) = (a->b) -> (b->c) -> (a->c)
application operator] $ = (a->b) -> a -> b