为什么 'Control.Applicative.Const' 没有 'Alternative' 实例
Why is there not 'Alternative' instance for 'Control.Applicative.Const'
Control.Applicative
中的 Const
函子有一个实例 Monoid a => Monoid (Const a b)
。还有一个例子Monoid m => Applicative (Const m)
。
因此,我希望还有一个实例 Monoid m => Alternative (Const m)
与 Monoid
的实例重合。这只是一个应该修复的遗漏,还是有更深层次的原因?
我相信是更深层次的原因。虽然 Alternative
似乎没有规范的规则集,但为了使 Alternative
有意义,Alternative
与其 Applicative
操作之间肯定应该存在关系(否则它只是一个任意的幺半群。)
This answer to Confused by the meaning of the 'Alternative' type class and its relationship to other type classes 陈述了这些法律
- Right distributivity (of
<*>
): (f <|> g) <*> a = (f <*> a) <|> (g <*> a)
- Right absorption (for
<*>
): empty <*> a = empty
- Left distributivity (of
fmap
): f <$> (a <|> b) = (f <$> a) <|> (f <$> b)
- Left absorption (for
fmap
): f <$> empty = empty
这对我来说很有意义。粗略地说,empty
和 <|>
对 pure
和 <$>
/<*>
就像 0 和 + 对 1 和 *.
现在,如果我们添加与 Monoid
/ Applicative
重合的实例 Monoid m => Alternative (Const m)
,则右律不成立。
例如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)
.
另请参阅:
- 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?
Control.Applicative
中的 Const
函子有一个实例 Monoid a => Monoid (Const a b)
。还有一个例子Monoid m => Applicative (Const m)
。
因此,我希望还有一个实例 Monoid m => Alternative (Const m)
与 Monoid
的实例重合。这只是一个应该修复的遗漏,还是有更深层次的原因?
我相信是更深层次的原因。虽然 Alternative
似乎没有规范的规则集,但为了使 Alternative
有意义,Alternative
与其 Applicative
操作之间肯定应该存在关系(否则它只是一个任意的幺半群。)
This answer to Confused by the meaning of the 'Alternative' type class and its relationship to other type classes 陈述了这些法律
- Right distributivity (of
<*>
):(f <|> g) <*> a = (f <*> a) <|> (g <*> a)
- Right absorption (for
<*>
):empty <*> a = empty
- Left distributivity (of
fmap
):f <$> (a <|> b) = (f <$> a) <|> (f <$> b)
- Left absorption (for
fmap
):f <$> empty = empty
这对我来说很有意义。粗略地说,empty
和 <|>
对 pure
和 <$>
/<*>
就像 0 和 + 对 1 和 *.
现在,如果我们添加与 Monoid
/ Applicative
重合的实例 Monoid m => Alternative (Const m)
,则右律不成立。
例如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)
.
另请参阅:
- 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?