News for hackers. Stuff that matters.
Re:Remove the ++ and –- operators by JoeAltmaier on Thursday December 03, 2015 @04:46PM (#10672903)
Removing ++ et al: ok, they have their problems.

But retaining x += 1? That one has always annoyed me. Why does '+' (and friends) get this special form, but not my functions? Just because they're built-in.

They are useful; no argument there. Largely because 'x' can be a complex reference, and you don't have to type it twice (and the compiler doesn't have to figure out that its the same expression twice). E.g. x=x+1 is short but (rec)FnRec(iRec) = (rec)FnRec(iRec) + 1; is not short. And the compiler gets some great hints when the '+=' form is used (don't calculate the reference twice).

I just want that for my stuff too! E.g. I may have a transformation method Xform(Foo&, Bar) that returns another Foo&. I want to say foo = Xform(foo, bar); but with 'foo' replaced by a complex reference. I have to say FnFooRef(iFoo, "primary", red) = Xform(FnFooRef(iFoo, "primary", red), bar)

instead of FnFooRef(iFoo, "primary", red) Xform= bar;

I want my own 'operators' with the 'op=' syntax supported.

Probably its not terribly useful any more; languages support immutable data and tuples and so much that don't work this way at all.

Re:Remove the ++ and –- operators by ridiculous_fish on Thursday December 03, 2015 @06:24PM (#10673500)
In Swift, += is a separate operator from +, and is defined within the confines of the language. It's not privileged in any particular way:

    func +=(inout lhs: Int, rhs: Int)
and you can just implement this.

You might object that special forms are still privileged, e.g. foo[idx]+=1. But in fact these are not special: one of the surprising features of Swift is that inouts work on computed properties. For example, say we add a mutable property highHalf on UInt64:

    extension UInt64 {
        var highHalf : UInt32 {
            get { return UInt32(self >> 32) }
            set { self = (self & 0xFFFFFFFF) | (UInt64(newValue) << 32) }
        }
    }
Now you can do this:

    var x = UInt64.max
    x.highHalf -= 1
So complex references can be used for any inout. That's how array indexing works.

Swift is the first language I've encountered that works this way; are there others?

Re:Remove the ++ and –- operators by ScottBurson on Thursday December 03, 2015 @06:52PM (#10673634)
> Swift is the first language I've encountered that works this way; are there others?

Lisp, of course :-) Common Lisp's SETF and related macros work this way. E.g.,

  (incf (ldb (byte 3 5) x))
would increment the "byte" (CL's term for an arbitrary bit field) of width 3 at offset 5 of X.

INCF is defined in terms of SETF. Of course, the set of macros that can update a place is user-extensible. So if you wanted one that multiplies the value in the place by two, you could just write something like this (the trailing "f" in the name, as you might guess, is the convention for such a macro):

  (define-modify-macro doublef () (lambda (x) (* x 2)))
then you could call it like this:

  (doublef (ldb (byte 3 5) x))
to double the value in the bit field.

(EDIT: used lambda expression instead of helper function.)

Re:Remove the ++ and –- operators by jonhohle on Thursday December 03, 2015 @07:08PM (#10673715)
Isn't this how C++ works as well? operator+= is definable for any user defined types and typically you'll add an overloaded operator[] which returns a reference so that things like operator+= works as you'd expect within the context of a collection.

I have some old code somewhere for images which I'm sure does something to the effect of:

    image[x, y] *= scale;
where Image::operator[] returns a Pixel&.
Re:Remove the ++ and –- operators by ridiculous_fish on Thursday December 03, 2015 @07:46PM (#10673878)
Not quite. C++'s references are syntactic sugar on top of pointers: a Foo& always needs a Foo to point to. But Swift's inouts are implemented as a pair of closures: a getter and a setter, which need not just modify a Foo.

Consider the much-hated vector<bool>, implemented as a packed bit array. Since you can't return a reference to a bit, operator[] must create a special wrapper class that holds a reference to the word and the bit offset, and then overload operator= and perform other tricks. It's famously leaky and gross.

In Swift, we can implement this optimization much more cleanly. inout lifetimes are always scoped, and when the scope ends, the new value is written back to the object via its setter. Our `inout boolean` is not backed by a boolean at all: it's backed by a getter and setter which can do arbitrary things, like mask and shift a word.

Re:Remove the ++ and –- operators by mikeash on Thursday December 03, 2015 @05:30PM (#10673217)
I may be missing your point, but there's no special casing or special forms going on in Swift.

In Swift, + and += are just operators. They're two separate operators which happen to do similar things. In Swift, an operator can be defined to mutate its left-hand operand, which += is defined to do. You can create your own operators that do that as well.

If you want to do it for methods, Swift has mutating methods which can change the thing they're sent to. In this case, you'd mark your Xform func as "mutating" and then you can write someComplexThing.Xform(bar) and it will mutate someComplexThing in place.

Of course, if you want to support both forms, you end up with a bit of redundancy as you have to define stuff twice. But the built-in stuff is the same way, and you can at least define one in terms of the other to cut down on duplication.

Re:Remove the ++ and –- operators by JoeAltmaier on Thursday December 03, 2015 @04:56PM (#10672987)
Another way to express this is, I'd like a language keyword for "left hand side of assignment". Then for x=x+1 I could say

     x = <LHS> + 1;
It could then get arbitrarily complex. E.g.

     x =  (<LHS> + 1) / atan(<LHS>) - <LHS>;
and no matter how complex 'x' was in practice, the compiler (and the code reader) could keep track of what was happening.
Re:Remove the ++ and –- operators by jbert on Thursday December 03, 2015 @05:04PM (#10673041)
Is there a significant benefit to this over using a new name for the result?

    y = (x + 1) / atan(x) - x;
    x = y; // If you're in a loop and updating some value
If would hope/imagine that a compiler could reduce the two to the same code - and I don't think it reads any worse. Is there a downside beyond the extra line of code?
Re:Remove the ++ and –- operators by JoeAltmaier on Thursday December 03, 2015 @05:09PM (#10673074)
To be clear: the assignment isn't the optimization; its the use of a symbol for 'x' on the rhs so that the compiler can recognize it. To illustrate that

    X &x = { complex reference expression for x }
    y = (x + 1) / atan(x) - x;
Now the compiler has the clues it needs to write good code. And with language support I don't have to introduce new names for each occurrence; just one name like <LHS> that readers can quickly learn.
Re:Remove the ++ and –- operators by jbert on Friday December 04, 2015 @08:25AM (#10676150)
> And with language support I don't have to introduce new names for each occurrence;

Having <LHS> as a name is only useful I think if you don't want to give it another name? I was asking what's the downside of giving it a name.

Re:Remove the ++ and –- operators by JoeAltmaier on Friday December 04, 2015 @10:00AM (#10676643)
Name proliferation is a famous issue. One-use names are evil.
Re:Remove the ++ and –- operators by jbert on Thursday December 10, 2015 @02:40AM (#10709401)
I disagree. Names are comments. You don't want more mutable state across large scopes, but using intermediate names can help comprehension.
Re:Remove the ++ and –- operators by LBarret on Monday December 07, 2015 @03:00AM (#10688358)
why ? Could you elaborate ?

Because from my point of view, it could be only the case only if the scopes are weak or underused, or names are bad (too short, ect). After SSA is all about one-use names.

Re:Remove the ++ and –- operators by jlg23 on Thursday December 03, 2015 @06:19PM (#10673475)
I think I get what you mean, but I cannot imagine a single example where your proposed <LHS> keyword would be a good solution: IMHO, if I need a keyword to make the RHS understandable to the reader and the (much smarter) compiler, a macro or function is called for to encapsulate the RHS in a named and documented unit of code.
Re:Remove the ++ and –- operators by eliteraspberrie on Thursday December 03, 2015 @06:05PM (#10673396)
Do you mean something like "compound assignment operators"? Apparently you can define custom operators like:

    func += (inout left: Vector2D, right: Vector2D) {
        left = left + right
    }
https://developer.apple.com/library/ios/documentation/Swift/...
Re:Remove the ++ and –- operators by dbpokorny on Thursday December 03, 2015 @06:22PM (#10673488)
Question of clarification: is this the same concept as Python's __iadd__? I was not aware that this was a "thing" in programming language design.

http://stackoverflow.com/questions/1047021/overriding-in-pyt...

Re:Remove the ++ and –- operators by Veedrac on Thursday December 03, 2015 @07:08PM (#10673717)
Looking at eliteraspberrie's example, not really. Python's __iadd__ and such are not able to reassign. There is no "inout" in Python. The assignment aspect of __iadd__ is done through self mutation (and an extra hard-coded assignment to support immutable variables).
Re:Remove the ++ and –- operators by ben-schaaf on Friday December 04, 2015 @06:33AM (#10675733)
The assignment aspect of __iadd__ is done like any other assignment in python. The one to one equivalent of eliteraspberrie's would be:

  class Vector2D:
      def __iadd__(self, other)
          return self + other
No "self mutation" as you suggest. a += b is equivalent to a = a.__iadd__(b)
Re:Remove the ++ and –- operators by Veedrac on Friday December 04, 2015 @07:31AM (#10675922)
> No "self mutation" as you suggest.

Your example would be the implementation for immutable Vector2Ds, and is implemented for you if you just wrote __add__. (I presume object.__iadd__ falls back to self.__add__.)

The only time you should actually override __iadd__ is for mutable objects, in which case it should look more like

  class Vector2D:
      def __iadd__(self, other)
          for i, x in enumerate(other):
              self[i] += x
          return self
That's the self mutation I was talking about.

Well, strictly that's not OK either, since operators shouldn't be duck-typed. Instead you should do

  class Vector2D:
      def __iadd__(self, other)
          if not isinstance(other, Vector2D):
              return NotImplemented

          for i, x in enumerate(other):
              self[i] += x
          return self
Re:Remove the ++ and –- operators by dbpokorny on Friday December 04, 2015 @01:33PM (#10678104)
> The only time you should actually override __iadd__ is for mutable objects

What would the rationale be for such a rule?

the docs don't mention anything like that https://docs.python.org/2/library/operator.html and I've never heard it before. In Python, neither integers nor strings are mutable and both support the "x += y" syntax.

The __iadd__ method works the same for both mutable and immutable objects AFAIK

Re:Remove the ++ and –- operators by Veedrac on Saturday December 05, 2015 @05:01AM (#10681438)
> What would the rationale be for such a rule?

Because __iadd__ automatically delegates to __add__. For immutable objects that's the best you can do, so there's no reason to write both.

Re:Remove the ++ and –- operators by nevdka on Thursday December 03, 2015 @05:42PM (#10673283)
Perl6 lets you define your own operators [0]. I haven't seen them used enough to know how it affects code readability, though.

[0] http://doc.perl6.org/language/functions#Defining_Operators

Re:Remove the ++ and –- operators by kamaal on Thursday December 03, 2015 @06:31PM (#10673537)
Code readability will increase, having an operator with tightly defined input(s) type(s) will in fact greatly increase readability and reusability.
Re:Remove the ++ and –- operators by stdbrouw on Thursday December 03, 2015 @05:46PM (#10673302)
Or akin to PHP's pass-by-reference ampersand, you could have something like `&x + 1` which would expand to `x = x + 1`. Dunno what the impact on code readability/maintainability would be, but it does sound nice.

Especially when doing straightforward data manipulations in R or Python, endless lines of `bla = map(bla, fn)` start to look crufty, so much so that Pandas in Python now allows you to add `inplace=True` to almost any data manipulation method to cut down on the verbosity. But then, sprinkling that keyword argument across every line isn't exactly better. Neither is endless chaining. Looks like we could still use some syntactic improvement.

Re:Remove the ++ and –- operators by dbpokorny on Thursday December 03, 2015 @06:18PM (#10673471)
Sounds fine to me, what changes to a standard tokenizer and parser would you make to carry out your plan?

I'm not saying this is a shining example of brilliant programming, but it is in a semi-working state and something "in a similar style" (that is, a three-pass tokenizer -> LR parser -> LR parser where scope information and other metadata is computed in the second pass and fed into the third) should be able to handle the changes you're talking about.

https://github.com/dbpokorny/autoclave/

Re:Remove the ++ and –- operators by kamaal on Thursday December 03, 2015 @06:26PM (#10673514)
>>Why does '+' (and friends) get this special form, but not my functions?

You are right, take a look at Perl 6 infix operators. You can define your own operator(treat it like a function, as such) and then use it.

https://perl6advent.wordpress.com/2013/12/22/day-22-a-catalo...

Re:Remove the ++ and –- operators by aembleton on Thursday December 03, 2015 @05:34PM (#10673248)
Kotlin allows you to overload the += for your own classes. You just create a function called plusAssign such that a += b translates to a.plusAssign(b)

https://kotlinlang.org/docs/reference/operator-overloading.h...

Re:Remove the ++ and –- operators by bcoates on Thursday December 03, 2015 @05:02PM (#10673025)
Other way around; z = x + y is a shorthand syntax for

  z <- copy(x)
  z += y
But you're otherwise right, it's annoying that this shorthand syntax isn't more generally available for user functions.
Re:Remove the ++ and –- operators by logicallee on Thursday December 03, 2015 @06:38PM (#10673573)
>But retaining x += 1? That one has always annoyed me. Why does '+' (and friends) get this special form, but not my functions?

The reason is that I don't want to see you escape your strings by writing

  input escapequotes= input
That's why. come on. who wants to read that?
Re:Remove the ++ and –- operators by Someone on Friday December 04, 2015 @04:31AM (#10675404)
But it would be

   input +'= input
and the reverse

   input -'= input
or, alternatively,

   input \'= input
and

   input !'= input
If you code does this often enough, that may even be useful (but also, your code would be bad)
Re:Remove the ++ and –- operators by jsprogrammer on Thursday December 03, 2015 @04:54PM (#10672977)
>Why does '+' (and friends) get this special form, but not my functions?

Your functions can get that (and other) special form. You need to use a language where you can define your own operators. Have you looked at C++, C#, Haskell, or LISP?

Re:Remove the ++ and –- operators by ryanschneider on Thursday December 03, 2015 @05:24PM (#10673178)
> You need to use a language where you can define your own operators. Have you looked at C++, C#, Haskell, or LISP?

Or, um, Swift. :)

http://nshipster.com/swift-operators/

Re:Remove the ++ and –- operators by chrislattner on Friday December 04, 2015 @11:26PM (#10680857)
More directly, check out: https://github.com/apple/swift/blob/master/stdlib/public/cor...

Which is where much of the Swift "language" is defined... in the standard library.

-Chris

Re:Remove the ++ and –- operators by dragonwriter on Thursday December 03, 2015 @05:04PM (#10673044)
> Your functions can get that (and other) special form. You need to use a language where you can define your own operators. Have you looked at C++, C#, Haskell, or LISP?

AFAIK, Lisp doesn't have syntactically-distinct operators at all just functions which may have names similar to operators used in other languages, and C# and C++ don't seem to support custom operators at all. [0]

OTOH, Perl 6 has robust support for custom operators.

[0] except that C++ has apparently been hacked to create custom operators with some limitations via macros [1]

[1] http://www.codeproject.com/Articles/31783/Custom-User-Define...

Re:Remove the ++ and –- operators by jsprogrammer on Thursday December 03, 2015 @05:27PM (#10673203)
What "operator" means will be language dependent. An operator is fundamentally just a function, so LISP fits.
Re:Remove the ++ and –- operators by JoeAltmaier on Thursday December 03, 2015 @04:57PM (#10672991)
Huh. C++? You can overload operators, but define your own? I must have missed something.
Re:Remove the ++ and –- operators by janvidar on Thursday December 03, 2015 @05:03PM (#10673032)
Well, I suppose you can #define your own?
Re:Remove the ++ and –- operators by winter_blue on Thursday December 03, 2015 @06:17PM (#10673466)
#define function(arg1, arg2, arg3) exists for creating macro functions, but nothing exists for naturally creating macro unary or binary operators in C and its descendants.
Re:Remove the ++ and –- operators by jsprogrammer on Thursday December 03, 2015 @05:25PM (#10673185)
Each language will have a different meaning of what exactly it means to "define your own". C++ restricts which symbols may be operators, but, you can "define your own +".
Re:Remove the ++ and –- operators by kibwen on Thursday December 03, 2015 @05:42PM (#10673282)
In practice it's very useful to distinguish between a language which "just" has operator overloading vs a language that allows custom user-defined symbolic operators. The existence of the latter is actually one of the few complaints that I have about Swift so far, but I'm sure many people will ardently disagree with me here. :P
Re:Remove the ++ and –- operators by Retra on Thursday December 03, 2015 @07:57PM (#10673923)
It's a wonderful feature for writing DSLs, but it's also confusing when you intermingle DSLs with the standard language. It really tends to balloon the amount of information you need to know to read others' code.