Feature request: Path append operators for strings
H. S. Teoh
hsteoh at quickfur.ath.cx
Fri Jul 5 11:16:36 PDT 2013
On Fri, Jul 05, 2013 at 10:44:43AM -0700, Walter Bright wrote:
> On 7/5/2013 9:17 AM, H. S. Teoh wrote:
> >Python uses +.
>
> There's much historical precedence for + meaning concatenation, and
> much historical experience with the resulting ambiguity.
Which leads to some nasty situations in Javascript, where sometimes what
you think is an int, is actually a string, and you wonder why your
calculation is producing strange results. Or vice versa, when you're
trying to concatenate strings, and get a strange large number instead.
> The famous example is:
>
> "123" + 4
>
> ? In D, the canonical problem is:
>
> int[] array;
>
> array + 4
>
> Does that mean append 4 to array, or add 4 to each element of array?
> What if you want to create a user defined type that supports both
> addition and concatenation?
>
> Use + for addition, ~ for concatenation, and all these problems go
> away.
It doesn't necessarily have to be ~, as long as it's something other
than + (or any other numerical binary operator). Perl uses '.', but in
D's case, that would be a bad idea, since you'd have ambiguity in:
auto x = mod1.x . mod2.y; // concatenation or long module path name?
It's not a problem in Perl, because Perl uses :: as module separator,
like C++.
Your example is somewhat faulty, though; adding 4 to each element of the
array would have to be written "array[] + 4", wouldn't it? You can't
make the [] optional, because if you have an array of arrays, then
you're in trouble:
int[][] aoa;
aoa ~ [1]; // append to outer array, or each inner array?
While it's possible to use type-matching to decide, it seems like a bug
waiting to happen. Much better if array <op> x always means apply <op>
to the entire array, and array[] <op> x to mean apply <op> to each array
element.
T
--
People tell me I'm stubborn, but I refuse to accept it!
More information about the Digitalmars-d
mailing list