# How to expand (not replace) the “+”, “>” infix operator on strings? [duplicate]

I went through the similar questions to overload the behavior of built-in operator, like How to overload the operator "*" as KroneckerProduct. The answers given there are usually to use new operator, instead of touching the built-in ones, as it might break how things work by default.

Defining a new infix operator works to a degree, especially at narrower context. But a remaining problem is there'll just be more and more different operators to be defined when the context expands. So I think a better way would be to re-use the existing ones if possible (give them new meaning for new context, without introducing ambiguity and breaking existing behaviors).

With that, I think of string. They're different from numbers, so is it possible to expand the behavior of built-in operators like "+" on strings? so that its behavior can be expanded when the operands are strings, and not breaking the default behavior:

In:= "ab" + "ac"

Out= "abac"

In:= 1 + 1

Out= 2

In:= "ab" > "ac"

Out= False

In:= 1 > 2

Out= False

• Just saw another similar question mathematica.stackexchange.com/questions/89706/…, with mentioning of upvalues, might be helpful. – liang Mar 22 at 5:01
• You can concatenate strings with <>. I would not try to overload + for this purpose. I believe that the risk that something will be severely broken by this change is very high. – Szabolcs Mar 22 at 8:43
• <> works for string concatination. But the fact one has to use a different operator in different context is not ideal, as explained in the question. We'll just end up with a tons of different operators, and each works for a different purpose. I've updated the question description to cover more purposes to highlight this. – liang Mar 23 at 0:24

Maybe this?

Unprotect[Plus];
Plus[s__String] := StringJoin[s];
Protect[Plus];


Let's try:

"b" + "a"

"ab"

Uh, it does not work because Plus has Attribute Orderless and you definitely do not want to remove that.

So no, it does not work.

• Couldn’t you do something like have it not be Orderless when the arguments are strings? – CA Trevillian Mar 23 at 4:23
• Unfrotunately no. According to ?Orderless, Orderless sorts the entries already before pattern matching. So you cannot circumvent it by pattern matching. – Henrik Schumacher Mar 23 at 6:57