在纯粹和liftA2方面,什么是适用的仿函数法则?

Ala*_*ell 11 haskell applicative

我正在玩pureliftA2(以及(<*>) = liftA2 id成为派生组合者)制定Applicative .

我可以想到一堆候选法则,但我不确定最小集合是什么.

  1. f <$> pure x = pure (f x)
  2. f <$> liftA2 g x y = liftA2 ((f .) . g) x y
  3. liftA2 f (pure x) y = f x <$> y
  4. liftA2 f x (pure y) = liftA2 (flip f) (pure y) x
  5. liftA2 f (g <$> x) (h <$> y) = liftA2 (\x y -> f (g x) (h y)) x y
  6. ...

Cir*_*dec 7

根据McBride和Paterson的法律Monoidal(第7节),我建议以下法律适用于liftA2pure.

左右身份

liftA2 (\_ y -> y) (pure x) fy       = fy
liftA2 (\x _ -> x) fx       (pure y) = fx
Run Code Online (Sandbox Code Playgroud)

关联

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)
Run Code Online (Sandbox Code Playgroud)

自然性

liftA2 (\x y -> o (f x) (g y)) fx fy = liftA2 o (fmap f fx) (fmap g fy)
Run Code Online (Sandbox Code Playgroud)

它不是立即显而易见的是,这些是足以覆盖的关系fmapApplicativepureliftA2.让我们看看我们是否可以从上述法律证明

fmap f fx = liftA2 id (pure f) fx
Run Code Online (Sandbox Code Playgroud)

我们将从努力开始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
Run Code Online (Sandbox Code Playgroud)

在这一点上,我们已经写fmap来讲liftA2,pure任何y; fmap完全由上述法律决定.尚未经证实的证据的其余部分由犹豫不决的作者留下作为坚定读者的练习.