Hacker News new | ask | show | jobs
by kyllo 3921 days ago
You cannot subtract a string

Maybe in Javascript you can't, but you sure could design a language where you could subtract strings, if you wanted to. You could treat the strings as two arrays of characters and subtract them. The result would be the characters that are in the first string but not in the second string. "Hello" - "o" would be "Hell".

I'm sure you could do this in Ruby by monkeypatching the string class to overload the minus method.

2 comments

> The result would be the characters that are in the first string but not in the second string

A result would be that, but I certainly would not call it the result.

Another result would be to treat the strings as byte arrays and subtract one byte from another, e.g. [a1,a2,a3] - [b1,b2,b3,b4] would result in [a1-b1, a2-b2, a3-b3, -b4]. I'm sure you could do any number of different "correct" operations. And then it's up to you, as a language designer, to decide what you think string-minus-string should actually do... and there is zero probability that everybody in the programming community will agree with your decision.

How would your method subtract "lo" from "Hello" and leave "Hel" instead of "He"? It gets complicated enough that I think you'd be re-implementing a more limited version of regex.

Also I was speaking in context of Javascript so I fail to see how this applies.

More of a general observation about how arbitrary the type juggling rules and operator overloadings in programming languages are.