minad / colorful-monoids

colorful-monoids: Styled console text output using ANSI escape sequences
MIT License
4 stars 1 forks source link

Colorful is not a monoid #1

Open enobayram opened 5 years ago

enobayram commented 5 years ago

I've just noticed that Colorful is not a lawful Monoid, because its <> implementation isn't associative: Value "a" <> (Value "b" <> Value "c") == (Value "a" <> Value "b") <> Value "c"

I wonder if it's possible to implement an Eq (and also an Ord) instance that respects associativity of <>. Or even better, a <> implementation that is truly associative.

minad commented 5 years ago

@enobayram You are right about the nested datatype. It is only monoidal in a weird effective sense, since the flattened result should look the same. This is similar to what pretty printers do. See for example http://hackage.haskell.org/package/wl-pprint-1.2.1/docs/src/Text.PrettyPrint.Leijen.html#Doc.

Maybe the datatype should be hidden. In this way the monoid law violation in the implementation could not be observed and the monoid laws would hold in an extrinsic sense.

Alternatively I could either restore the monoid laws on the value level by replacing the Pair (Colored a) (Colored a) constructor by List ![Colored a], but this wouldn't be efficient. An alternative could be List !(DList a).

enobayram commented 5 years ago

@minad sorry I didn't respond earlier. IMHO hiding the datatype could be an equally good option if it weren't for backward compatibility concerns. With that concern, though, I think DList is a cleaner solution. That said, would DList be efficient enough while showColoreding?