Why is there not 'Alternative' instance for 'Control.Applicative.Const'

醉酒当歌 提交于 2019-12-30 08:06:27

问题


There is an instance Monoid a => Monoid (Const a b) for the Const functor from Control.Applicative. There is also an instance Monoid m => Applicative (Const m).

I would therefore expect that there is also an instance Monoid m => Alternative (Const m) that coincides with the one for Monoid. Is this just an omission that should be fixed, or is there a deeper reason?


回答1:


I believe there is a deeper reason. While it seems there is no canonical set of rules for Alternative, in order for Alternative to make sense, there definitely ought to be a relationship between Alternative and its Applicative operations (otherwise it'd be just an arbitrary monoid.)

This answer to Confused by the meaning of the 'Alternative' type class and its relationship to other type classes states these laws

  1. Right distributivity (of <*>):  (f <|> g) <*> a = (f <*> a) <|> (g <*> a)
  2. Right absorption (for <*>):  empty <*> a = empty
  3. Left distributivity (of fmap):  f <$> (a <|> b) = (f <$> a) <|> (f <$> b)
  4. Left absorption (for fmap):  f <$> empty = empty

which make a lot of sense to me. Roughly speaking, empty and <|> are to pure and <$>/<*> what 0 and + are to 1 and *.

Now if we add instance Monoid m => Alternative (Const m) that coincides with the one for Monoid / Applicative, the Right- laws don't hold.

For example, 2. fails, because

empty <*> (Const x)
= Const mempty <*> Const x    -- by the suggested definition of Alternative
= Const $ mempty `mappend` x  -- by the definition of <*> for COnst
= Const x                     -- by monoid laws

which isn't equal to empty = Const mempty. Similarly, 1. fails, a simple counter-example is setting f = Const (Sum 1); g = Const (Sum 1) ; a = Const (Sum 1).

See also:

  • What are the relations between Alternative, MonadPlus(LeftCatch) and MonadPlus(LeftDistributive)?
  • What’s an example of a Monad which is an Alternative but not a MonadPlus?


来源:https://stackoverflow.com/questions/28681260/why-is-there-not-alternative-instance-for-control-applicative-const

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!