Ala*_*ell 11 haskell applicative
我正在玩pure和liftA2(以及(<*>) = liftA2 id成为派生组合者)制定Applicative .
我可以想到一堆候选法则,但我不确定最小集合是什么.
f <$> pure x = pure (f x)f <$> liftA2 g x y = liftA2 ((f .) . g) x yliftA2 f (pure x) y = f x <$> yliftA2 f x (pure y) = liftA2 (flip f) (pure y) xliftA2 f (g <$> x) (h <$> y) = liftA2 (\x y -> f (g x) (h y)) x y根据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
在这一点上,我们已经写fmap来讲liftA2,pure任何y; fmap完全由上述法律决定.尚未经证实的证据的其余部分由犹豫不决的作者留下作为坚定读者的练习.
| 归档时间: | 
 | 
| 查看次数: | 762 次 | 
| 最近记录: |