本文介绍了Monoid vs MonadPlus的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Monad 和 Monoid 都很新颖,最近也了解到 MonadPlus 。从我看到的 Monoid 和 MonadPlus 都提供了一个带有关联二元操作和标识的类型。 (我用数学术语称这是一个半群。)那么 Monoid 和 MonadPlus ?

解决方案

是配备有关联二元操作的结构。 是一个具有二元操作标识元素的半群。



monads和semigroups



每个monad都必须遵守明确指出 mplus 和 mzero 必须在 ma 上为任意 A 。再次,我们得到一个由 a 索引的monids类。注意 MonadPlus 和 Monoid : Monoid 表示某些单一类型满足monoidal规则,而 MonadPlus 表示对于所有可能的 a 类型 ma 满足monoidal法则。这是一个更强大的条件。因此,一个 MonadPlus 实例形成两个不同的代数结构:一类半群>>< / code>以及一类monoids与 mplus 和 mzero 。 (这并不罕见,例如大于零的自然数集 {1,2,...} 形成一个半群,其中 + 和一个含有×和 1 的monoid。)


I am very new to both Monads and Monoids and recently also learned about MonadPlus. From what I see, Monoid and MonadPlus both provide a type with a associative binary operation and an identity. (I'd call this a semigroup in mathematical parlance.) So what is the difference between Monoid and MonadPlus?

解决方案

A semigroup is a structure equipped with an associative binary operation. A monoid is a semigroup with an identity element for the binary operation.

Monads and semigroups

Every monad has to adhere to the monad laws. For our case, the important one is the associativity law. Expressed using >>=:

(m >>= f) >>= g     ≡   m >>= (\x -> f x >>= g)

Now let's apply this law to deduce the associativity for >> :: m a -> m b -> m b:

(m >> n) >> p       ≡ (m >>= \_ -> n) >>= \_ -> p
                    ≡ m >>= (\x -> (\_ -> n) x >>= \_ -> p)
                    ≡ m >>= (\x -> n >>= \_ -> p)
                    ≡ m >>= (\x -> n >> p)
                    ≡ m >> (n >> p)

(where we picked x so that it doesn't appear in m, n or p).

If we specialize >> to the type m a -> m a -> m a (substituting b for a), we see that for any type a the operation >> forms a semigroup on m a. Since it's true for any a, we get a class of semigroups indexed by a. However, they are not monoids in general - we don't have an identity element for >>.

MonadPlus and monoids

MonadPlus adds two more operations, mplus and mzero. MonadPlus laws state explicitly that mplus and mzero must form a monoid on m a for an arbitrary a. So again, we get a class of monoids indexed by a.

Note the difference between MonadPlus and Monoid: Monoid says that some single type satisfies the monoidal rules, while MonadPlus says that for all possible a the type m a satisfies the monoidal laws. This is a much stronger condition.

So a MonadPlus instance forms two different algebraic structures: A class of semigroups with >> and a class of monoids with mplus and mzero. (This is not something uncommon, for example the set of natural numbers greater than zero {1,2,...} forms a semigroup with + and a monoid with × and 1.)

这篇关于Monoid vs MonadPlus的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 13:41