mathlex-eval
Numerical evaluator for mathematical expression ASTs produced by mathlex. Compile once with constants, evaluate many times with different arguments. Supports N-dimensional broadcasting via Cartesian product semantics.
Quick start
Add to Cargo.toml:
[]
= "0.1"
= "0.3"
Compile and evaluate an expression:
use HashMap;
use ;
use ;
// Build AST for: 2*x + 3
let ast = Binary ;
// Compile with no constants
let compiled = compile.unwrap;
// Evaluate with x = 5
let mut args = new;
args.insert;
let result = eval.unwrap.scalar.unwrap;
// result = Real(13.0)
Broadcasting
Array arguments produce Cartesian product outputs. Scalars broadcast to all positions.
use EvalInput;
let mut args = new;
args.insert;
args.insert;
let handle = eval.unwrap;
// handle.shape() == [3, 2]
// Output grid:
// y=10 y=20
// x=1 [ 11, 21 ]
// x=2 [ 14, 24 ]
// x=3 [ 19, 29 ]
Three consumption modes:
handle.scalar()— 0-d result, errors if output is not scalarhandle.to_array()— eager N-dArrayD<NumericResult>handle.iter()— lazy per-element streaming
Complex numbers
Real inputs produce real results. Complex promotion happens automatically when needed:
- Imaginary unit constant (
MathConstant::I) sqrtof negative numberslnof negative numbersasin/acosoutside[-1, 1]- Complex
EvalInputarguments
Architecture
Two-phase compile/eval:
- Compile — validate AST, substitute constants, resolve variables, fold constant subexpressions
- Evaluate — substitute arguments, compute results with broadcasting
This separation enables constant folding at compile time and efficient repeated evaluation.
Supported expressions
Accepted AST variants: Integer, Float, Rational, Complex, Variable, Constant, Binary (add, sub, mul, div, pow, mod), Unary (neg, factorial), Function (23 built-in), Sum, Product.
All other variants (derivatives, integrals, limits, vectors, matrices, etc.) return CompileError::UnsupportedExpression.
Built-in functions
sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh, exp, ln, log2, log10, log, sqrt, cbrt, abs, floor, ceil, round, min, max
Feature flags
| Flag | Default | Description |
|---|---|---|
serde |
yes | Serialize/Deserialize for CompiledExpr and NumericResult |
parallel |
no | Rayon-based parallel broadcasting in to_array() |
ffi |
no | Swift FFI via swift-bridge |
API reference
| Type | Role |
|---|---|
compile() |
Compile AST with constants into CompiledExpr |
eval() |
Create lazy eval handle from CompiledExpr + arguments |
CompiledExpr |
Opaque compiled expression |
EvalHandle |
Lazy result handle (consume via scalar/to_array/iter) |
EvalIter |
Streaming result iterator |
NumericResult |
Real or Complex result value |
EvalInput |
Argument value: scalar, array, or iterator |
CompileError |
Compilation failure (7 variants) |
EvalError |
Evaluation failure (5 variants) |
Full documentation: docs.rs/mathlex-eval
License
MIT