为什么选择MonadPlus而不是Monad + Monoid? [英] Why MonadPlus and not Monad + Monoid?
问题描述
我试图理解 MonadPlus
背后的动机。为什么如果已经存在类型类 Monad
和 Monoid
?
当然, Monoid
的实例是具体类型,而 Monad
的实例需要单个类型参数。 (请参阅 Monoid vs MonadPlus ,以获得有用的解释。)但是难道你不能重写任何类型的
(MonadPlus m)=> ...
作为 Monad
和 Monoid
?
(Monad m,Monoid(ma))= > ...
从 guard
函数从例如, Control.Monad
。它的实现是:
guard ::(MonadPlus m)=>布尔 - > m()
guard True = return()
guard False = mzero
我能够仅使用 Monad
和 Monoid
来实现它:
guard'::(Monad m,Monoid(m()))=>布尔 - > m()
guard'True = return()
guard'False = mempty
<有人可以澄清 MonadPlus
和 Monad
+ Monoid
但是难道你不能重写
(MonadPlus m)=> ...
作为Monad和Monoid的组合吗?
blockquote>
没有。在你链接的问题的顶部答案中,关于MonadPlus与Monoid的规律已经有了很好的解释。但即使我们忽略了类型类法则也有不同。
Monoid(m a)=> ...
意味着ma
必须是一个特殊的a
调用者,但MonadPlus m
意味着ma
必须是所有a
。所以MonadPlus a
更加灵活,这种灵活性在以下四种情况下有帮助:
如果我们不想告诉调用者我们打算使用什么
a
>。
MonadPlus m = > ...
而不是Monoid(m SecretType)=> ...
如果我们想使用多个不同的
a
。
MonadPlus m => ...
而不是(Monoid(m Type1),Monoid(m Type2),...)=> ...
- c $ c>我们需要。
如果我们想要使用无限多个不同的
a
。
MonadPlus m => ...
而不是不可能。
MonadPlus m => ...
而不是不可能。
I'm trying to understand the motivation behind the
MonadPlus
. Why is it necessary if there are already the typeclassesMonad
andMonoid
?Granted, instances of
Monoid
are concrete types, whereas instances ofMonad
require a single type parameter. (See Monoid vs MonadPlus for a helpful explanation.) But couldn't you rewrite any type constraint of(MonadPlus m) => ...
as a combination of
Monad
andMonoid
?(Monad m, Monoid (m a)) => ...
Take the
guard
function fromControl.Monad
, for example. Its implementation is:guard :: (MonadPlus m) => Bool -> m () guard True = return () guard False = mzero
I was able to implement it using only
Monad
andMonoid
:guard' :: (Monad m, Monoid (m ())) => Bool -> m () guard' True = return () guard' False = mempty
Could someone please clarify the real difference between
MonadPlus
andMonad
+Monoid
?解决方案But couldn't you rewrite any type constraint of
(MonadPlus m) => ...
as a combination of Monad and Monoid?
No. In the top answer to the question you link, there is already a good explanation about the laws of MonadPlus vs. Monoid. But there are differences even if we ignore the typeclass laws.
Monoid (m a) => ...
means thatm a
has to be a monoid for one particulara
chosen by the caller, butMonadPlus m
means thatm a
has to be a monoid for alla
. SoMonadPlus a
is more flexible, and this flexibility is helpful in four situations:
If we don't want to tell the caller what
a
we intend to use.
MonadPlus m => ...
instead ofMonoid (m SecretType) => ...
If we want to use multiple different
a
.
MonadPlus m => ...
instead of(Monoid (m Type1), Monoid (m Type2), ...) => ...
If we want to use infinitely many different
a
.
MonadPlus m => ...
instead of not possible.If we don't know what
a
we need.MonadPlus m => ...
instead of not possible.
这篇关于为什么选择MonadPlus而不是Monad + Monoid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!