Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom operators #54

Open
mingchen opened this issue Nov 18, 2024 · 2 comments
Open

Custom operators #54

mingchen opened this issue Nov 18, 2024 · 2 comments

Comments

@mingchen
Copy link

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.

@nicklockwood
Copy link
Owner

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: "/")

@mingchen
Copy link
Author

Thank you. Looking forward to an improvement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants