interp

Function interp 

Source
pub fn interp<'a>(
    expression: &str,
    ctx: Option<Rc<EvalContext>>,
) -> Result<Real>
Expand description

Interprets a string as a mathematical expression, evaluates it, and returns the result.

This is the primary function for evaluating expressions. It parses the expression string, builds an Abstract Syntax Tree (AST), and then evaluates the AST using the provided context.

§Parameters

  • expression: The mathematical expression to evaluate as a string
  • ctx: An optional evaluation context containing variables, constants, and functions

§Returns

  • Ok(value): The result of evaluating the expression
  • Err(error): An error describing what went wrong during parsing or evaluation

§Examples

Basic usage without context:

use exp_rs::engine::interp;

// Evaluate a simple expression
let result = interp("2 + 3 * 4", None).unwrap();
assert_eq!(result, 14.0);

// Using built-in functions and constants
let result = interp("sin(pi/6) + cos(pi/3)", None).unwrap();
assert!((result - 1.0).abs() < 0.0001);

Using a context with variables:

use exp_rs::context::EvalContext;
use exp_rs::engine::interp;
use std::rc::Rc;

let mut ctx = EvalContext::new();
ctx.set_parameter("x", 5.0);
ctx.set_parameter("y", 10.0);

let result = interp("x + y", Some(Rc::new(ctx))).unwrap();
assert_eq!(result, 15.0);

Error handling:

use exp_rs::engine::interp;
use exp_rs::error::ExprError;

match interp("2 + * 3", None) {
    Ok(_) => panic!("Expected an error"),
    Err(ExprError::Syntax(_)) => {
        // This is expected - there's a syntax error in the expression
    }
    Err(e) => panic!("Unexpected error: {:?}", e),
}