[swift-evolution] Allowing Characters for use as Custom Operators

Jo Albright me at jo2.co
Fri Jan 8 15:28:14 CST 2016


I promise, this is my last idea to be thrown at this. Instead of characters in operators...

Would the core team be open to having an operatoralias keyword that allows an operator to be masked by an identifier.

Learning & Teaching Example :

operatoralias plus = +

let apples = 5 + 5
let apples = 5 plus 5

With extension :

let apples = 5 . plus ( 5 )

---------------------------------------------------------------------------------

Learning & Teaching Example :

operatoralias incrementedBy = +=

updatedValue += 10
updatedValue incrementedBy 10

With extension :

updatedValue . incrementedBy ( 10 )

---------------------------------------------------------------------------------

Readability & Code Reduction Example :

typealias Point = (x: CGFloat,y: CGFloat)

infix operator >>>> { }

func >>>> (lhs: CGContextRef?, rhs: Point) -> CGContextRef? {
    
    CGContextMoveToPoint(lhs, rhs.x, rhs.y); return lhs
    
}

operatoralias moveTo = >>>> // operator alias for custom operator

let context = UIGraphicsGetCurrentContext()

context moveTo (10,10) addLineTo (20,20) strokeWith UIColor.redColor()

Or if SVG letters used (less readable, but also less footprint) :

context M (10,10) L (20,20) stroke UIColor.redColor()

I know this looks a lot like a chained method and very close to the same amount of code to be written… however it is slightly easier to read without all of the function punctuation in between :

context.moveTo(10,10)?.addLineTo(20,20)?.strokeWith.(UIColor.redColor())


I believe there is an opportunity here that won’t truly be appreciated until it is in use. But will not argue that it is very close to what is currently available and does not have a huge impact in the current vision of things.

Thanks for humoring my imagination. :) 


 Nerd . Designer . Developer
Jo Albright


> On Jan 8, 2016, at 2:26 PM, Chris Lattner <clattner at apple.com> wrote:
> 
> 
>> On Jan 7, 2016, at 9:49 PM, Jacob Bandes-Storch <jtbandes at gmail.com> wrote:
>> 
>> Some other languages provide special syntax to use a binary function as infix:
>> 
>> 
>> Haskell:
>>    foo a b    -- is equivalent to
>>    a `foo` b
>> 
>> Mathematica:
>>    Foo[a, b]  (*is equivalent to*)
>>    a~Foo~b
> 
> Ok, then yes, introducing a magic syntax would be technically feasible (though not backticks, since they are used for something else).
> 
> This is still extremely unlikely to be accepted though.  Additional language complexity needs to pay for itself, and the win here is so small that it doesn’t seem worth it.
> 
> -Chris
> 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160108/224659df/attachment.html>


More information about the swift-evolution mailing list