简体   繁体   中英

What is the name of this monoid law?

In the documentation for Data.Monoid , it states the following laws should be satisfied:

mappend mempty x = x
mappend x mempty = x
mappend x (mappend y z) = mappend (mappend x y) z
mconcat = foldr mappend mempty

My understanding of these is that the first 2 are identity, and the third is associativity.

But what is the law in the fourth line? Identity again, but for mconcat ?

Mathematically, the definition of a monoid requires the existence of something like mempty and something like mappend , satisfying the first three laws: left and right identity, and associativity.

The mconcat method has been added to the class to reflect the fact that accumulation in a list is often what one does with monoids. The fourth law is the executable specification of mconcat : indeed, that very law is the line of code which gives the default implementation of mconcat . Making mconcat a member of the class means that, per Monoid instance, you are free to give mconcat a more efficient implementation, just as long as it agrees with the default.

It's not clear to me that making mconcat reimplementable in this way is a particularly big win. I'd tend to avoid mconcat in favour of (the confusingly named) fold .

The purpose of mconcat is not to provide any more information about the monoid; it is an implementation detail. It is a convenience function, but one that might be implemented more efficiently than its default definition. When infinite lists are considered, "more efficient" can mean "possible".

Consider the Product monoid. The following never terminates, using the default definition of mconcat :

mconcat (map Product [0..])

even though it should be obvious that any list of integers containing 0 should produce 0. However, if you were to redefine the function as

mconcat = foldr (\acc v -> if acc == Product 0 then Product 0 else mappend acc v) empty

Then the product of an infinite list containing at least one zero would still terminate. (Of course, an infinite list of of non-zero values would still never terminate, but this mconcat is still more efficient for large lists that contain an "early" zero.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM