String concatenation via ++ or <>

Viewed 91

I'm wondering whether there is a reason to use one over the other for string concatenation:

λ> "foo" ++ "bar"
"foobar"
λ> "foo" <> "bar"
"foobar"

Operator ++ is defined as list concatenation while <> is an associative binary operator of a semigroup. In GHC.Base we even have that for lists they are the same:

instance Semigroup [a] where
        (<>) = (++)

Is there any pro/con to use one over the other? Typically I prefer <> since this means I can switch between types String and Text more easily. Any other pros/cons?

1 Answers

I agree, <> is preferrable because it works on text types other than Prelude.String.

The only downside I can think of: more polymorphism can also mean that the types become ambiguous. Specifically, when -XOverloadedStrings is active, you can't just pass a string literal to an input-polymorphic function anymore. Sometimes just a little bit of extra information helps resolve these ambiguities. When using ++, the compiler knows it must be a list representation, and then the a ~ Char constraint in the IsString [a] instance is sufficient to infer that you want it to be a plain old String. But when you're using <>, it's likely enough that one of the operands already constrains the type anyway, and also it's arguable whether it might be better to always add an explicit signature in ambiguous situations, rather than relying on subtle details like ++ vs <>.

Related