According to the definition or a monoid the binary operator must be associative e.g. 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.