nicklockwood / Expression

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

Support ^ as pow operator #49

Closed vanniktech closed 1 year ago

vanniktech commented 1 year ago

I don't think that pow(2, 3) is actually understood by anyone. Instead it feels more naturally to write 2^3.

Is it possible to support this using symbols? If not, would it be possible to include this as a standard operator?

nicklockwood commented 1 year ago

Yes, it's completely possible - just define a "^" operator for your expression. The only reason this isn't built-in is that ^ isn't universally recognised as the exponent operator - C uses it as bitwise xor for example.

EDIT: here's how:

let expression = "2 ^ 3"

let result = try Expression(
    expression,
    symbols: [
        .infix("^"): { pow($0[0], $0[1]) }
    ]
).evaluate()

print(result) // 8
vanniktech commented 1 year ago

I must say I really like the API that you expose. Well done!