简体   繁体   中英

Haskell - Implementing Monoid what happens if the operator is not associative

According to the definition or a monoid the binary operator must be associative eg A op (B op C) == (A op B) op C .

The base mconcat definition in haskell is:

mconcat = foldr mappend mempty

Since I know the implementation details of the mconcat function, would anything bad happen from defining and using fake monoids where the function isn't associative? Like for example defining instances for subtraction or division.

Could this be useful or am I missing the point?

Nothing bad would happen in terms of type safety: Your programs will still not crash.

But a data structure relying on your Monoid instance might give unexpected or wrong results.

Consider a tree that is re-balanced upon insertion, and that provides a way to combine its elements using their Monoid instance. Then the re-balancing, which is supposed to be an internal operation and not visible to you becomes observable, and referential transparency is “morally broken” – same input (up to supposedly hidden internals), but different output.

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