AppleScript Calculator: Take selected text equation & calculate the result
Over on StackOverflow you will find these related questions:
- Equation (expression) parser with precedence?
- Smart design of a math parser?
For a discussion about parsing expressions, see:
- Parsing Expressions
The Burden of AppleScript
AppleScript is not a language to relish writing a parser in. The language is great for many things but not text manipulation. The language is Turing Complete, so your project is possible, but difficult.
AppleScript is an Open Scripting Architecture (OSA) dialect and maybe you would be willing to consider another OSA dialect for this project, such as JavaScript. While JavaScript is not ideal, you will find more resources and guides to help you. You can also mix and match Script Editor compiled AppleScript and JavaScript scripts.
Use bc
Consider piping the selected text to bc
and returning the result:
set theInput to "(4.0+55.0)/2.0"
set myCalculation to "echo 'scale=1;" & (theInput) & "' | bc"
set myResult to do shell script myCalculation
This approach avoids reinventing the wheel and uses the built-in command line calculator included with macOS, bc
.