Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why has Haskell decided against using `+` for string (list) concatenation?

Tags:

haskell

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.

like image 317
John Smith Avatar asked Nov 30 '22 14:11

John Smith


1 Answers

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.

like image 66
Mark Seemann Avatar answered Dec 05 '22 06:12

Mark Seemann