我们可以用Alternative而不能用Monoid做什么?



我读为什么MonadPlus而不是Monad + Monoid?我理解理论上的区别,但我不能找出实际的区别,因为对于List来说,它看起来是一样的。

mappend [1] [2] == [1] <|> [2]

是的。可能有不同的实现

mappend (Just "a") (Just "b") /= (Just "a") <|> (Just "b")

但是我们可以用与Alternative

相同的方式实现Maybe Monoid
instance Monoid (Maybe a) where
  Nothing `mappend` m = m
  m `mappend` _ = m

那么,有人能展示一个代码示例来解释Alternative和Monoid之间的实际区别吗?

这个问题不是"为什么是MonadPlus而不是Monad + Monoid?"

这里有一个非常简单的例子,可以使用Alternative:

import Control.Applicative
import Data.Foldable
data Nested f a = Leaf a | Branch (Nested f (f a))
flatten :: (Foldable f, Alternative f) => Nested f a -> f a
flatten (Leaf x) = pure x
flatten (Branch b) = asum (flatten b)

现在让我们对Monoid做同样的事情:

flattenMonoid :: (Foldable f, Applicative f) => Nested f a -> f a
flattenMonoid (Leaf x) = pure x
flattenMonoid (Branch b) = fold (flattenMonoid b)

当然,这不能编译,因为在fold (flattenMonoid b)中,我们需要知道扁平化会产生一个容器,其中的元素是Monoid的实例。所以让我们把它添加到上下文中:

flattenMonoid :: (Foldable f, Applicative f, Monoid (f a)) => Nested f a -> f a
flattenMonoid (Leaf x) = pure x
flattenMonoid (Branch b) = fold (flattenMonoid b)

啊,但是现在我们有一个问题,因为我们不能满足递归调用的上下文,它需要Monoid (f (f a))。所以让我们把它添加到上下文中:

flattenMonoid :: (Foldable f, Applicative f, Monoid (f a), Monoid (f (f a))) => Nested f a -> f a
flattenMonoid (Leaf x) = pure x
flattenMonoid (Branch b) = fold (flattenMonoid b)

好吧,这只会让问题变得更糟,因为现在递归调用需要更多的东西,即Monoid (f (f (f a)))

如果我们能写

flattenMonoid :: ((forall a. Monoid a => Monoid (f a)), Foldable f, Applicative f, Monoid (f a)) => Nested f a -> f a

或者只是

flattenMonoid :: ((forall a. Monoid (f a)), Foldable f, Applicative f) => Nested f a -> f a

,我们可以:不写forall a. Monoid (f a),我们写Alternative f。(我们也可以编写一个类型类来表达第一个更容易满足的约束。)

最新更新