views:

175

answers:

3

We're all familiar with the pre- and post-increment operators, e.g.

c++;    // c = c + 1
++c;    // ditto

and the "combined operators" which extend this principle:

c += 5;    // c = c + 5
s .= ", world";    // s = s . ", world"; e.g. PHP

I've often had a need for a 'post-combined operator', which would allow:

s =. "Hello ";    // s = "Hello " . s

Obviously, this is only really useful with non-commutable operators and the meaning is altered from pre-/post-increment, even though the syntax is borrowed.

Are you aware of any language that offers such an operator, and why isn't it more common?

+2  A: 

A basic objection to the example as-given is that it'd create ambiguity:

a=-5;    //'a = -5' or 'a =- 5'?
b=*p;    //'b = *p' or 'b =* p'?
c=.5;    //'c = .5' or 'c =. 5'?

Edit: But no, I'm not aware of any languages that use them. Presumably this is because they were omitted from C from whence most other languages derive their basic operators.

And yeah, I'd love to see them in the languages I use.

A: 

None that I know about, and I don't think that there will be, as it's a meta-meta-command.

To explain, the original operators (for numbers) came from C where they mapped directly to machine code operations. This allowed the programmer to do optimization, since the early compiler didn't.
So,

x=x+1;

and

x+=1;

and

x++;

would generate three different assembler outputs.

Now, adding += for string is a meta-command. It doesn't map to an opcode, it just follows and extends the pattern.

James Curran
+2  A: 

Combined 'op=' operators are shorthand for var = var op predicate, but op doesn't have to be anything in particular. The '.' operator happens to be shorthand for an "append" operation in a number of languages, but there's nothing stopping you from defining a "prepend" operation — or even changing append to prepend — in any language that allows overloading an operator on whatever data type you want to work with (or on any object you might use to contain that data otherwise). If you want to make textvar /= newtext shorthand for textobj = textobj->prepend(newtext) there's nothing stopping you.

That said, you should probably never do this, as there's no way to change an existing operator without causing loads of confusion. It is substantially easier (and clearer) to change your statement order so that you can go left to right, or use a specific function such as unshift to prepend things without any ambiguity.

Zed