Crates.io | expr-solver |
lib.rs | expr-solver |
version | 1.0.6 |
source | src |
created_at | 2024-02-09 16:55:20.870296 |
updated_at | 2024-02-10 17:08:06.95809 |
description | Solves a mathematical expression while following precedence and associativity. |
homepage | https://github.com/prashantrahul141/expr-solver |
repository | https://github.com/prashantrahul141/expr-solver |
max_upload_size | |
id | 1134154 |
size | 27,516 |
Solves a mathematical expression while following precedence and associativity.
The crate provides one public api function.
fn resolve(input_string: String) -> Result<f64, String>
This takes mathematical expressions as String, and returns a Result enum with solved value or incase of an error, error string.
use expr_solver::resolve;
// simple binary expression.
resolve("2+2".to_string()); // Ok(2.0)
// follows precendence, 2 + (2 _ 2) and NOT (2 + 2) _ 2
resolve("2+2*2".to_string()); // Ok(6.0);
// unary expression.
resolve("-2".to_string()); // Ok(-2.0)
// even chain them. -(-2)
resolve("--2".to_string()); // Ok(2.0)
// binary and unary in one expression.
resolve("2+-2".to_string()); // Ok(0.0)
// gives syntax error.
resolve("2)2".to_string()); // Err(String);
There are three steps involved
Breaks the input string into indiviual tokens.
This uses a Pratt Parsing technique to parse the stream of tokens into Abstract Syntax Tree (AST).
Uses a 'Tree-Walk' interpreter to evalute the AST.