简体   繁体   中英

What are the applicative functor laws in terms of pure and liftA2?

I'm playing around with formulating Applicative in terms of pure and liftA2 (so that (<*>) = liftA2 id becomes a derived combinator).

I can think of a bunch of candidate laws, but I'm not sure what the minimal set would be.

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

Based on McBride and Paterson's laws for Monoidal (section 7) I'd suggest the following laws for liftA2 and pure .

left and right identity

liftA2 (\_ y -> y) (pure x) fy       = fy
liftA2 (\x _ -> x) fx       (pure y) = fx

associativity

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)

naturality

liftA2 (\x y -> o (f x) (g y)) fx fy = liftA2 o (fmap f fx) (fmap g fy)

It isn't immediately apparent that these are sufficient to cover the relationship between fmap and Applicative 's pure and liftA2 . Let's see if we can prove from the above laws that

fmap f fx = liftA2 id (pure f) fx

We'll start by working on fmap f fx . All of the following are equivalent.

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

At this point we've written fmap in terms of liftA2 , pure and any y ; fmap is entirely determined by the above laws. The remainder of the as-yet-unproven proof is left by the irresolute author as an exercise for the determined reader.

Per the online book, Learn You A Haskell:Functors, Applicative Functors and Monoids , the Appplicative Functor laws are bellow but reorganized for formatting reasons; however, I am making this post community editable since it would be useful if someone could embed derivations:

    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

Note:

function composition]  (.) = (a->b) -> (b->c) -> (a->c)
application operator]    $ = (a->b) -> a -> b

Found a treatment on Reddit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM