expr-solver

Crates.ioexpr-solver
lib.rsexpr-solver
version1.0.6
sourcesrc
created_at2024-02-09 16:55:20.870296
updated_at2024-02-10 17:08:06.95809
descriptionSolves a mathematical expression while following precedence and associativity.
homepagehttps://github.com/prashantrahul141/expr-solver
repositoryhttps://github.com/prashantrahul141/expr-solver
max_upload_size
id1134154
size27,516
Prashant (prashantrahul141)

documentation

README

Expression Solver

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.

Examples

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);

Inner workings

There are three steps involved

1. Lexical Analysis.

Breaks the input string into indiviual tokens.

2. Parser

This uses a Pratt Parsing technique to parse the stream of tokens into Abstract Syntax Tree (AST).

3. Interpreting

Uses a 'Tree-Walk' interpreter to evalute the AST.

Commit count: 0

cargo fmt