【问题标题】:Why is there not 'Alternative' instance for 'Control.Applicative.Const'为什么'Control.Applicative.Const'没有'Alternative'实例
【发布时间】:2015-02-23 18:56:55
【问题描述】:

Control.Applicative 中的 Const 函子有一个实例 Monoid a => Monoid (Const a b)。还有一个实例Monoid m => Applicative (Const m)

因此,我希望还有一个实例 Monoid m => Alternative (Const m)Monoid 的实例一致。这只是一个应该修复的遗漏,还是有更深层次的原因?

【问题讨论】:

  • 关于Alternative没什么。就像MonadPlus,甚至没有人同意它的法律应该是什么,它最引人注目的用例是一种双关语。随心所欲。

标签: haskell applicative monoids alternative-functor


【解决方案1】:

我相信更深层次的原因。虽然Alternative 似乎没有一套规范的规则,但为了让Alternative 有意义,Alternative 和它的Applicative 操作之间肯定应该有关系(否则它只是一个任意幺半群。)

This answerConfused by the meaning of the 'Alternative' type class and its relationship to other type classes 规定了这些法律

  1. 正确分配(<*>):  (f <|> g) <*> a = (f <*> a) <|> (g <*> a)
  2. 右吸收(<*>):  empty <*> a = empty
  3. 左分布(fmap):  f <$> (a <|> b) = (f <$> a) <|> (f <$> b)
  4. 左吸收(fmap):  f <$> empty = empty

这对我来说很有意义。粗略地说,empty<|> 对应于 pure<$>/<*> 0 和 + 对应于 1 和 *。

现在,如果我们添加实例 Monoid m => Alternative (Const m)Monoid / Applicative 的实例一致,则右定律不成立。

比如2.失败,因为

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

不等于empty = Const mempty。同样,1.失败,一个简单的反例是设置f = Const (Sum 1); g = Const (Sum 1) ; a = Const (Sum 1)

另见:

【讨论】:

  • 非常感谢您详细、精心编写的回答。我同意这些法律确实有意义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-09
相关资源
最近更新 更多