7

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?

poida
  • 3,403
  • 26
  • 26

1 Answers1

12

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.

Joachim Breitner
  • 25,395
  • 6
  • 78
  • 139
  • 1
    I'd argue that's worse than crashing. But I guess there's no way around it if someone wishes to insist that `a-(b-c) == (a-b)-c` should hold... – John L Nov 22 '14 at 16:45