|
Answer» Define and implement a custom power ^^ operator that satisfies the following requirements: - As arguments, it accepts two Ints.
- The first parameter is returned after raising it to the second parameter's power.
- The EQUATION is correctly evaluated using the conventional algebraic sequence of operations.
- Overflow errors are not taken into account.
There are two steps to creating a new custom operator: - Declaration: The "operator" keyword is used in the declaration to indicate the type of the operator (unary or BINARY), the sequence of letters that make up the operator, associativity, and precedence. The operator here is ^^ and the type is infix (binary) in this case. Equal precedence operators ^^ should evaluate the equation from right to left (associativity is right). The following is the declaration step:
precedencegroup ExponentPrecedence { HIGHERTHAN: MultiplicationPrecedence associativity: right}infix operator ^^: ExponentPrecedence- Implementation: In Swift, there is no set precedence for exponential operations. Exponents should be calculated before multiplication and division in the normal algebra sequence of operations. As a result, you will need to set custom precedence that puts them ahead of multiplication. The following is the implementation step:
func ^^(base: Int, exponent: Int) -> Int { let left = DOUBLE(base) let right = Double(exponent) let powerValue = pow(left, right) return Int(powerValue)}It can be noted that as the program does not take overflows into consideration, in the event of the OPERATION producing a result that Int can't represent, for example, a value more than Int.max, then a runtime error occurs.
|