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?
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.)
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&.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.
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.
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. 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? 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.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.
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.
func += (inout left: Vector2D, right: Vector2D) {
left = left + right
}
https://developer.apple.com/library/ios/documentation/Swift/...http://stackoverflow.com/questions/1047021/overriding-in-pyt...
class Vector2D:
def __iadd__(self, other)
return self + other
No "self mutation" as you suggest. a += b is equivalent to a = a.__iadd__(b)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 selfWhat 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
Because __iadd__ automatically delegates to __add__. For immutable objects that's the best you can do, so there's no reason to write both.
[0] http://doc.perl6.org/language/functions#Defining_Operators
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.
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.
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...
https://kotlinlang.org/docs/reference/operator-overloading.h...
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.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? 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)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?
Or, um, Swift. :)
Which is where much of the Swift "language" is defined... in the standard library.
-Chris
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...
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.