nicklockwood / Expression

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

Custom operators #54

Open mingchen opened 4 hours ago

mingchen commented 4 hours ago

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 commented 4 hours ago

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 commented 2 hours ago

Thank you. Looking forward to an improvement.