[−][src]Crate rsc
This crate is specifically used for one thing: turning expressions inside of a string into a value. This crate acts as a scientific calculator, and includes several functions.
If you need a portion of the calculator changed or removed, please fork it, and make your changes. We encourage others to change RSC to their liking. You do not need to attribute anything to us. This is MIT licensed software.
Anyone can easily create a Computer and begin working with expressions. Computers also remember variables using a HashMap. You can create and begin using the preconfigured Computer like so:
use rsc::computer::Computer; fn main() { let mut c = Computer::<f64>::default(); // or // let mut c: Computer<f64> = Default::default(); assert!(c.eval("x = 5").unwrap() == 5.0); assert!(c.eval("x^2").unwrap() == 25.0); }
In most cases a simple eval
should be all you need, but just as many times you may need
to directly access the tokens and AST. Some reasons may include:
- For performance or caching; lexing and parsing an expression only once, to calculate it later hundreds of times in a loop.
- Better error messages or visual information for what is happening.
use rsc::{ lexer::tokenize, parser::{parse, Expr}, computer::Computer, }; fn main() { let tokens = tokenize("x^2", true).unwrap(); let ast = parse(&tokens).unwrap(); let mut computer = Computer::<f64>::default(); for x in 2..=5 { let mut ast = ast.clone(); // Replace instances of variable reference 'x' with f64 value x from loop ast.replace(&Expr::Identifier("x".to_owned()), &Expr::Constant(x as f64), false); // or this could be done like: // computer.variables. println!("{}", computer.compute(&ast).unwrap()); } } // Output: // 4 // 9 // 16 // 25
Creating an Empty Computer
Constructing a Computer with Computer::<f64>::default()
will initialize it with default
variables: PI and E, and default functions: sin
, cos
, tan
, log
, and sqrt
.
To get a Computer with absolutely no default values, please construct one like so:
let mut c = Computer::new(); /// ... using the computer
Modules
computer | This module is for taking instructions generated by the parser (an AST) and producing real numbers. |
lexer | For making notable symbols and words out of text. |
parser | For using the symbols generated by the lexer and making sense of them in the context of mathematical expressions. |
Enums
EvalError | An error that groups together all three error types: computer::ComputeError,
parser::ParserError, and lexer::LexerError. Produced when using |
Functions
eval | Turn an expression inside a string into a number. If you are looking for more control, you may want to use the lexer, parser, and computer modules individually. |