nicklockwood / Expression

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

Question: Can multiplication be done with parentheses? #39

Closed antingle closed 1 year ago

antingle commented 2 years ago

I am currently working on creating a calculator and have been using this framework for expression parsing, which has been going wonderfully so far. I am wondering if there is a way to implement multiplication with parentheses (for example "4(2)" = 8). If this is not possible with the current state of the framework, is it something worth adding in?

nicklockwood commented 2 years ago

@ingleanthony yes, this is possible. You need to provide a custom implementation for the () operator, like this:

let expression = Expression("4(2)", symbols: [
      .infix("()"): { args in args[0] * args[1] },
])
print(try expression.evaluate()) // prints 8