[swift-evolution] [Proposal] Custom operators

Антон Жилин antonyzhilin at gmail.com
Sun Apr 3 07:13:16 CDT 2016


Right, the proposal in its current form does not really aim to resolve such
conflicts, although it makes them occur less often by "merging" precedence
and associativity when possible.

At first, I also tried to resolve such conflicts by naming operators. But I
found that compiler instructions will be too complex in some cases:

#operator(+, name: numericAdd, fixity: infix, associativity: left)
#operator(+, name: arrayAppend, fixity: infix, associativity: right)

func numericAdd(left: A, right: B) -> C
func numericAdd(left: B, right: C) -> B
func arrayAppend(left: A, right: A) -> B
func arrayAppend(left: B, right: C) -> A

A() + B() + C()

Compiler will have to find by brute-force that this expression can only
represent arrayAppend(A(), arrayAppend(B(), C())), and others result in
errors. To me, this scheme seems pretty absurd.

That said, it might be a good idea to add visibility for operators.
Hiding already imported operators, on the other hand, would be inconsistent
with othr elements of the language. It is currently impossible to hide
contents of module A from C where C imports B and B imports A. Not that I'm
against such a feature in general.

- Anton


2016-04-03 14:26 GMT+03:00 Ross O'Brien <narrativium+swift at gmail.com>:

> There is a problem here of duplicated operators or custom precedence, and
> how that gets passed between modules.
> Assume there are three modules, A, B and C. B defines a custom operator
> **. A and C each define a custom operator ++, and their meanings are
> different (though, even if their meanings were the same, I'm not sure if
> they could unify).
>
> Module D uses A and B as dependencies and sets a custom precedence on ++
> and **. Module E uses B and C and has a different precedence on ++ and **.
> You're working on Module F which uses D and E. Which ++ and which
> precedence does F get implicitly?
>
> I'm wondering whether we can treat operators the way we recently decided
> to treat selectors: if there is an ambiguity, it should be possible not
> just to specify which module they came from, but their fixity or argument
> types. If module D decides that '++' should refer to 'traditional postfix
> number incrementation', and F decides that it should be an infix 'conjoin
> two numbers as a string and turn the result into a number (e.g. 5 ++ 4 ->
> 54)' then a #selector-like operator signature would come in really handy.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160403/7967b46e/attachment.html>


More information about the swift-evolution mailing list