nicklockwood / Expression

A cross-platform Swift library for evaluating mathematical expressions at runtime
MIT License
829 stars 51 forks source link

Ability to use ^ instead of pow(x, y) #38

Closed antingle closed 2 years ago

antingle commented 2 years ago

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 type 4^2 instead.

nicklockwood commented 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
antingle commented 2 years ago

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!

FliiFe commented 1 year ago

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 ?

nicklockwood commented 1 year ago

Ah, I see. No, the precedence is hard-coded I'm afraid.