Since I had trouble googling this question I thought I'd post it here.
I'm just interested in the logic behind it or wether it's just the creators' preference to use ++
instead. I mean, using a typeclass for strings that concatenates two strings (or rather lists) with +
does not seem too hard to imagine.
Edit: I should add, that in Haskell one has to suspect reasons behind it, because +
and ++
are functions defined in typeclasses, whereas in java the usage of +
for string concatenation is just part of the language's syntax and therefor subject only to the creators preference/opinion. (The answers so far suggest that I was right about my suspicion.)
Also haskell comes from a mathematical background and is deeply influenced by mathematical syntax, so there might be deeper reasons than just preference/opinion.
typeclass for strings that concatenates two strings
Such a typeclass exists, although the operator isn't +
, but <>
:
Prelude> :m +Data.Monoid
Prelude Data.Monoid> "foo" <> "bar"
"foobar"
While ++
concatenates lists, the <>
operator is more general, since it combines any two values of a given Monoid
instance.
As other people have pointed out, +
is reserved for Num
instances. Why isn't the Monoid
binary operator called +
, then? Because addition is only one of infinitely many monoids; multiplication is another:
Prelude Data.Monoid> Sum 2 <> Sum 3
Sum {getSum = 5}
Prelude Data.Monoid> Product 2 <> Product 3
Product {getProduct = 6}
Choosing something like <>
as 'the' monoidal operator is preferred exactly because it carries little semantic baggage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With