nicklockwood / Expression

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

Getting sub expressions during evaluation #45

Open VolceOntra opened 1 year ago

VolceOntra commented 1 year ago

Problem: I want to add a postfix % operator that takes in the last valid expression and transform it, however (and I'm still learning this library) it seems without a lot of parsing it's kind of challenging -- is there a way to transform something like this

10 + 2% to equal 10 + (10*2/100)

or

20 2 + 10% would give access to the last evaluated expression of (20 2) and the main argument 10 when getting the post fix callback for %

nicklockwood commented 1 year ago

@VolceOntra sorry, I don't think this is possible right now. The precedence for postfix operators is always higher than for infix, so without adding parentheses, it's not possible for the % to operate on the entire previous expression.

The syntax tree isn't currently public, but you could maybe do something hacky, like preprocess the string to add parentheses in before passing it to Expression.