3
$\begingroup$

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
$\endgroup$
  • 2
    $\begingroup$ Just saw another similar question mathematica.stackexchange.com/questions/89706/…, with mentioning of upvalues, might be helpful. $\endgroup$ – liang Mar 22 at 5:01
  • 1
    $\begingroup$ 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. $\endgroup$ – Szabolcs Mar 22 at 8:43
  • $\begingroup$ <> 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. $\endgroup$ – liang Mar 23 at 0:24
5
$\begingroup$

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.

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.