Core Expression System
The Expression type is the foundation of MathHook. Expressions are immutable, 32-byte cache-optimized structures representing mathematical constructs from numbers to complex symbolic operations.
Code Examples
Creating Expressions with Macros
Use expr!() and symbol!() macros for ergonomic expression creation
use mathhook::prelude::*;
let x = symbol!(x);
let y = symbol!(y);
// Basic arithmetic
let sum = expr!(x + y);
let product = expr!(x * y);
let power = expr!(x ^ 2);
// Complex nested expressions
let complex = expr!(sin(x ^ 2) + cos(y ^ 2));
Immutability and Operations
All operations return new expressions, original unchanged
let expr = expr!(x + 1);
let doubled = expr.mul(&expr!(2)); // Returns new expression
// `expr` is unchanged - still x + 1
// Safe to use in multiple threads
use std::sync::Arc;
let expr_arc = Arc::new(expr!(x ^ 2));
let clone = Arc::clone(&expr_arc);
Canonical Forms and Equality
Automatic normalization ensures equivalent expressions are equal
let expr1 = expr!(x + y);
let expr2 = expr!(y + x);
assert_eq!(expr1, expr2); // True - both normalized to x + y
// Flattening
let nested = expr!((x + y) + z);
// Automatically flattened to Add(x, y, z)
// Identity removal
let identity = expr!(x + 0);
assert_eq!(identity.simplify(), expr!(x));
Pattern Matching and Structure
Work with expression structure using pattern matching
use mathhook::Expression;
match expr {
Expression::Add(terms) => {
println!("Sum with {} terms", terms.len());
}
Expression::Mul(factors) => {
println!("Product with {} factors", factors.len());
}
Expression::Pow(base, exp) => {
println!("Power: {} ^ {}", base, exp);
}
Expression::Function(name, args) => {
println!("Function {} with {} args", name, args.len());
}
_ => {}
}