Expression icon indicating copy to clipboard operation
Expression copied to clipboard

Custom operators

Open mingchen opened this issue 1 year ago • 2 comments

First, thank you for this library—it's simple yet powerful.

As a calculator, I'd like to use x ÷ instead of * /. I tried to pass custom symbols

let expression = "2+3x5"
var symbols: [Expression.Symbol: Expression.SymbolEvaluator] = [:]
symbols[.infix("x")] = { $0[0] * $0[1] }
symbols[.infix("÷")] = { $0[0] / $0[1] }
let expr = Expression(expression, symbols: symbols)

However this introduce a new issue for following express:

2+3x5

It expect 17 instead of 25. The issue is that x should be calculate first before + and -. Since x is a custom operator, it can not be treat the same as *.

If + - * / operators can be customized would be great and can avoid this kind of issue.

mingchen avatar Nov 18 '24 21:11 mingchen

The issue is that there's currently no way to set operator precedence externally.

I'll think about a good way to expose this.

Probably the best solution for you for now is just to do a character replacement on the string before passing it to expression e.g. string.replacingOccurences(of: "÷", with: "/")

nicklockwood avatar Nov 18 '24 22:11 nicklockwood

Thank you. Looking forward to an improvement.

mingchen avatar Nov 18 '24 23:11 mingchen