https://github.com/neuodev/calc-rs
Calculator to perform basic and nested arithmetic operations on raw expressions.
https://github.com/neuodev/calc-rs
Last synced: about 1 year ago
JSON representation
Calculator to perform basic and nested arithmetic operations on raw expressions.
- Host: GitHub
- URL: https://github.com/neuodev/calc-rs
- Owner: neuodev
- Created: 2022-08-21T06:01:18.000Z (almost 4 years ago)
- Default Branch: master
- Last Pushed: 2023-10-02T06:18:45.000Z (almost 3 years ago)
- Last Synced: 2025-07-05T03:40:51.330Z (about 1 year ago)
- Language: Rust
- Homepage:
- Size: 3.31 MB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# `calc-rs`
Calculator to perform basic arithmetic operations on raw expressions.
## Preview
## Examples
```bash
? Expression: (2 * 2) + (4 * 3)
#> 16
? Expression: (12 / 2) * [30 * 3]
#> 540
? Expression: 1.0 * 0.1
#> 0.1
? Expression: 0.1 * (100 * 14)
#> 140
? Expression: 0.1 / 20 + 14
#> 14.005
? Expression: (1 * (2 + 1)) + 1
#> 4
```
# How it works
we call the whole input an **experssion** (`expr` for short). Every `expr` might be made of combination of `terms`, `operators` and other `expr`.
For example take this input `1 + 2 [14 * (22 + 4)] + 7`.
- `1 + 2 [14 * (22 + 4)] + 7` this is as whole called `expr`
- `1` is a `term`
- `+` is an operator
- `[14 * (22 + 4)]` another `expr`
- `(22 + 4)` another `expr`
Using this recursive relationship we can evaluate the `expr` in this manner
```bash
Result (+)
├── 1
├── 2
├── [14 * (22 + 4)] (*)
│ ├── 14
│ └── (22 + 4) (+)
│ ├── 22
│ └── 4
└── 7
```
I am using a combination of **recursion** and **regular expressions** to be able to perform **nested** operations.
at the core you will find this single `regexp`
```rs
let re = Regex::new(r"(\(|\[)(?P[^\)\(\]\[]+)(\)|\])").unwrap();
```
This regexp should match any nested experssion that is inside `()` or `[]` or both. It will match **_from inside out_** for example consider this experssion `[()()]` it will match `()` then `()` then the whole `[() ()]` experssion
I am sure if i tried to read this `regexp` on week from now I will not be able to do so! for this reason I am using interactive tool called [regexp101.com](https://regex101.com/r/Z8ELny/1) that make `regexp` easy to develop
if you follow [this link](https://regex101.com/r/Z8ELny/1) you should see this
## Supported operations
```rs
enum Op {
Plus, // '+'
Mins, // '-'
Multi, // '*' | 'x'
Div, // '/'
}
```