Haskell is a monoid implementation, what happens if the operator is not associative

According to the definition or monoid, the binary operator must be associative, for example. A op (B op C) == (A op B) op C

The basic definition of mconcat in haskell:

 mconcat = foldr mappend mempty 

Since I know the details of the implementation of the mconcat function, could there be something bad from defining and using fake monoids, where the function is not associative? As, for example, the definition of instances for subtraction or division.

Could this be helpful or am I missing a point?

+5
source share
1 answer

Nothing wrong with type safety: your programs will not be broken anyway.

But a data structure based on your Monoid instance may produce unexpected or incorrect results.

Consider a tree that is rebalanced when inserted, and provides a way to combine its elements using a Monoid instance. Then re-balancing, which should be an internal operation and not visible to you, becomes observable, and referential transparency "morally broken" - the same input (up to the supposedly hidden internal elements), but a different conclusion.

+11
source

Source: https://habr.com/ru/post/1207470/


All Articles