[][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 Calculator and begin working with expressions. Calculators also remember variables using a HashMap. You can create and begin using the Calculator like so:

extern crate rsc;
use rsc::computer::Computer;

fn main() {
    let mut c = Computer::new();

    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.
extern crate rsc;
use rsc::lexer::tokenize;
use rsc::parser::{Expr, parse};
use rsc::computer::Computer;
fn main() {
    let expr = "x^2";
    let tokens = tokenize(expr).unwrap();
    let ast = parse(&tokens).unwrap();
    let mut computer = Computer::new();
    for x in 2..=5 {
        let mut ast = ast.clone();
        ast.replace(&Expr::Identifier("x"), &Expr::Constant(x as f64), false);
        println!("{}", computer.compute(&ast).unwrap());
// Output:
// 4
// 9
// 16
// 25



This module is for taking instructions generated by the parser (an AST) and producing real numbers.


For making notable symbols and words out of text.


For using the symbols generated by the lexer and making sense of them in the context of mathematical expressions.





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.