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

问题描述 投票:11回答:2

我正在玩pureliftA2(以便(<*>) = liftA2 id成为派生组合者)。

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

  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. ...
haskell applicative
2个回答
7
投票

根据McBride和Paterson的laws for Monoidal(第7节),我建议对liftA2pure采用以下法律。

左右身份

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)

目前尚不清楚这些是否足以涵盖fmapApplicativepureliftA2之间的关系。让我们看看我们是否可以从上述法律证明

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

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


-1
投票

根据在线书籍Learn You A Haskell:Functors, Applicative Functors and 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

Found a treatment on Reddit

© www.soinside.com 2019 - 2024. All rights reserved.