The plus sign +
is used for addition and for string concatenation, but its companion: the minus sign, -
, is generally not seen for trimming of strings or some other case other than subtraction. What could be the reason or limitations for that?
Consider the following example in JavaScript:
var a = "abcdefg";
var b = "efg";
a-b == NaN
// but
a+b == "abcdefgefg"
Best Answer
In short, there aren’t any particularly useful subtraction-like operations on strings that people have wanted to write algorithms with.
The
+
operator generally denotes the operation of an additive monoid, that is, an associative operation with an identity element:It makes sense to use this operator for things like integer addition, string concatenation, and set union because they all have the same algebraic structure:
And we can use it to write handy algorithms like a
concat
function that works on a sequence of any “concatenable” things, e.g.:When subtraction
-
gets involved, you usually talk about the structure of a group, which adds an inverse −A for every element A, so that:And while this makes sense for things like integer and floating-point subtraction, or even set difference, it doesn’t make so much sense for strings and lists. What is the inverse of
"foo"
?There is a structure called a cancellative monoid, which doesn’t have inverses, but does have the cancellation property, so that:
This is the structure you describe, where
"ab" - "b" == "a"
, but"ab" - "c"
is not defined. It’s just that we don’t have many useful algorithms that use this structure. I guess if you think of concatenation as serialisation, then subtraction could be used for some kind of parsing.