5 ms·
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 n
by JoeAltmaier 11y ago
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.
- jsprogrammer 11y ago>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?
- JoeAltmaier 11y agoHuh. C++? You can overload operators, but define your own? I must have missed something.
- janvidar 11y agoWell, I suppose you can #define your own?
- winter_blue 11y ago#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.
- jsprogrammer 11y agoEach 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 +".
- kibwen 11y agoIn 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
- Retra 11y agoIt'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.
- dragonwriter 11y ago> 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-Defined-Operators-in-C http://www.codeproject.com/Articles/31783/Custom-User-Define...
- jsprogrammer 11y agoWhat "operator" means will be language dependent. An operator is fundamentally just a function, so LISP fits.
- ryanschneider 11y ago> 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/ http://nshipster.com/swift-operators/
- chrislattner 11y agoMore directly, check out: https://github.com/apple/swift/blob/master/stdlib/public/core/Policy.swift 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
- JoeAltmaier 11y agoAnother 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.
- jbert 11y agoIs 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?
- JoeAltmaier 11y agoTo 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.
- jbert 11y ago> 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.
- JoeAltmaier 11y agoName proliferation is a famous issue. One-use names are evil.
- 11y ago
- bcoates 11y agoOther 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.
- mikeash 11y agoI 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.
- aembleton 11y agoKotlin 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.html https://kotlinlang.org/docs/reference/operator-overloading.h...
- nevdka 11y agoPerl6 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 http://doc.perl6.org/language/functions#Defining_Operators
- kamaal 11y agoCode readability will increase, having an operator with tightly defined input(s) type(s) will in fact greatly increase readability and reusability.
- stdbrouw 11y agoOr 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.
- eliteraspberrie 11y agoDo 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/Conceptual/Swift_Programming_Language/AdvancedOperators.html#//apple_ref/doc/uid/TP40014097-CH27-ID28 https://developer.apple.com/library/ios/documentation/Swift/...
- dbpokorny 11y agoQuestion 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-python-iadd-method http://stackoverflow.com/questions/1047021/overriding-in-pyt...
- Veedrac 11y agoLooking 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).
- ben-schaaf 11y agoThe 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)
- Veedrac 11y ago> 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
- dbpokorny 11y agoSounds 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/ https://github.com/dbpokorny/autoclave/
- ridiculous_fish 11y agoIn 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?
- ScottBurson 11y ago> 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.)
- jonhohle 11y agoIsn'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&.
- 11y ago
- kamaal 11y ago>>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-catalogue-of-operator-types/ https://perl6advent.wordpress.com/2013/12/22/day-22-a-catalo...
- logicallee 11y ago>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?
- Someone 11y agoBut 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)