pub enum Expr {
Const(f64),
Var(String),
Add(Box<Expr>, Box<Expr>),
Mul(Box<Expr>, Box<Expr>),
Pow(Box<Expr>, Box<Expr>),
Neg(Box<Expr>),
Fn(MathFn, Box<Expr>),
}Expand description
A symbolic expression AST.
Sub is represented as Add(a, Neg(b)) and Div as Mul(a, Pow(b, Const(-1))).
§Examples
let expr = var("x") + constant(1.0);
let mut vars = HashMap::new();
vars.insert("x".to_string(), 2.0);
assert!((expr.eval(&vars).unwrap() - 3.0).abs() < 1e-10);Variants§
Const(f64)
Numeric constant.
Var(String)
Named variable.
Add(Box<Expr>, Box<Expr>)
Addition: lhs + rhs.
Mul(Box<Expr>, Box<Expr>)
Multiplication: lhs * rhs.
Pow(Box<Expr>, Box<Expr>)
Exponentiation: base ^ exp.
Neg(Box<Expr>)
Negation: -expr.
Fn(MathFn, Box<Expr>)
Function application: f(arg).
Implementations§
Source§impl Expr
impl Expr
Sourcepub fn eval(&self, vars: &HashMap<String, f64>) -> Result<f64>
pub fn eval(&self, vars: &HashMap<String, f64>) -> Result<f64>
Evaluate the expression given concrete variable bindings.
§Examples
let expr = constant(2.0) * var("x") + constant(1.0);
let vars = HashMap::from([("x".to_string(), 3.0)]);
assert!((expr.eval(&vars).unwrap() - 7.0).abs() < 1e-10);Sourcepub fn substitute(&self, var: &str, replacement: &Expr) -> Expr
pub fn substitute(&self, var: &str, replacement: &Expr) -> Expr
Replace every occurrence of var with replacement.
§Examples
let expr = var("x") + constant(1.0);
let replaced = expr.substitute("x", &constant(5.0));
assert!((replaced.eval(&HashMap::new()).unwrap() - 6.0).abs() < 1e-10);Sourcepub fn free_variables(&self) -> HashSet<String>
pub fn free_variables(&self) -> HashSet<String>
Collect all free variable names in the expression.
§Examples
let expr = var("x") + var("y") * constant(2.0);
let vars = expr.free_variables();
assert!(vars.contains("x"));
assert!(vars.contains("y"));
assert_eq!(vars.len(), 2);Sourcepub fn is_zero(&self) -> bool
pub fn is_zero(&self) -> bool
Returns true if the expression is Const(0.0).
§Examples
assert!(constant(0.0).is_zero());
assert!(!constant(1.0).is_zero());Sourcepub fn is_one(&self) -> bool
pub fn is_one(&self) -> bool
Returns true if the expression is Const(1.0).
§Examples
assert!(constant(1.0).is_one());
assert!(!constant(2.0).is_one());Trait Implementations§
impl StructuralPartialEq for Expr
Auto Trait Implementations§
impl Freeze for Expr
impl RefUnwindSafe for Expr
impl Send for Expr
impl Sync for Expr
impl Unpin for Expr
impl UnsafeUnpin for Expr
impl UnwindSafe for Expr
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more