How to declare exponent/power operator with new precedencegroup in Swift 3?

狂风中的少年 提交于 2019-12-19 05:44:35

问题


There's been a change in Swift 3 for Xcode 8 beta 6 and now I'm not able to declare my operator for power as I did before:

infix operator ^^ { }
public func ^^ (radix: Double, power: Double) -> Double {
    return pow((radix), (power))
}

I've read a bit about it and there's a new change been introduced in Xcode 8 beta 6

From this I'm guessing I have to declare a precedence group and use it for my operator like this:

precedencegroup ExponentiativePrecedence {}

infix operator ^^: ExponentiativePrecedence
public func ^^ (radix: Double, power: Double) -> Double {
    return pow((radix), (power))
}

Am I going in the right direction to make this work? What should I put inside the {} of the precedence group?

My final aim is to be able to make power operations with a simple operator in swift, e.g.:

10 ^^ -12
10 ^^ -24

回答1:


Your code already compiles and runs – you don't need to define a precedence relationship or an associativity if you're simply using the operator in isolation, such as in the example you gave:

10 ^^ -12
10 ^^ -24

However, if you want to work with other operators, as well as chaining together multiple exponents, you'll want to define a precedence relationship that's higher than the MultiplicationPrecedence and a right associativity.

precedencegroup ExponentiativePrecedence {
    associativity: right
    higherThan: MultiplicationPrecedence
}

Therefore the following expression:

let x = 2 + 10 * 5 ^^ 2 ^^ 3

will be evaluated as:

let x = 2 + (10 * (5 ^^ (2 ^^ 3)))
//          ^^    ^^    ^^--- Right associativity
//          ||     \--------- ExponentiativePrecedence > MultiplicationPrecedence
//           \--------------- MultiplicationPrecedence > AdditionPrecedence,
//                            as defined by the standard library

The full list of standard library precedence groups is available on the evolution proposal.



来源:https://stackoverflow.com/questions/39116205/how-to-declare-exponent-power-operator-with-new-precedencegroup-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!