Closed antingle closed 2 years ago
@ingleanthony I didn't want to make this part of the standard feature set originally because ^ is used in some languages to mean bitwise XOR. Expression is extensible though, so you can add your own operators:
let expression = Expression("2 ^ 3", symbols: [
.infix("^"): { params in pow(params[0], params[1]) },
])
let result = try expression.evaluate() // 8
I see, that makes sense. Thank you for sharing how to extend Expression with this. I figured there was a way to do it, but could not figure it out right away. Thank you for a great framework!
This implementation does not work, as the infix operator does not take precedence over addition. This makes for bizarre maths like : 1-2^6
= 1
.
Is there an option to impose precedence ?
Ah, I see. No, the precedence is hard-coded I'm afraid.
I believe that using ^ as an alternate operator for powers would be a very beneficial addition. For example, instead of typing
pow(4, 2)
, one could type4^2
instead.