[英]What are the applicative functor laws in terms of pure and liftA2?
我正在使用pure
和liftA2
來配制Applicative(因此(<*>) = liftA2 id
成為派生組合子)。
我可以想到一堆候選法則,但我不確定最小集合是什么。
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
基於McBride和Paterson的Monoidal
定律 (第7節),我建議對liftA2
和pure
進行以下定律。
左右身份
liftA2 (\_ y -> y) (pure x) fy = fy
liftA2 (\x _ -> x) fx (pure y) = fx
關聯
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)
自然性
liftA2 (\x y -> o (f x) (g y)) fx fy = liftA2 o (fmap f fx) (fmap g fy)
目前尚不清楚這些是否足以涵蓋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
和任何y
寫了fmap
; fmap
完全由上述法律決定。 尚未經證實的證據的其余部分由猶豫不決的作者留下作為堅定讀者的練習。
根據在線書籍, 了解你的Haskell:Functors,Applicative Functors和Monoids ,Appplicative Functor法律如下,但由於格式原因進行了重組; 但是,我正在使這個帖子社區可編輯,因為如果有人可以嵌入派生將是有用的:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.