3

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
liang
  • 589
  • 2
  • 12
  • 2
    Just saw another similar question https://mathematica.stackexchange.com/questions/89706/redefining-a-built-in-operator, with mentioning of upvalues, might be helpful. – liang Mar 22 '20 at 05:01
  • 1
    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 '20 at 08: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 '20 at 00:24

1 Answers1

5

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.

Henrik Schumacher
  • 106,770
  • 7
  • 179
  • 309