pub struct FunctionBag { /* private fields */ }Expand description
An extensible registry of user-defined symbolic functions, used by
parse::parse_with_functions to make runtime-constructed
functions recognisable by the string parser.
Built-in functions (sin, cos, clamp, etc.) are not stored in
the bag – the parser falls back to function_by_name for any
name the bag doesn’t carry, so built-ins are always available
regardless of what’s in the bag. An empty bag means “built-ins
only”, which is what parse::parse uses.
Names registered in the bag shadow built-ins with the same name.
§Registering a function
Pick the entry point that fits how you have the function in hand:
add1/add2– register a closure of arity 1 / 2, typically one produced bysimple_func1/simple_func2/extern_func1/extern_func2. The bag invokes it once with placeholder symbols to extract name, params, and kind.addN– register an n-ary closure overVec<E>. Pairs withsimple_func/simple_func_derivs/extern_func. No upper arity bound.add– register an already-formedExpr::Funcvalue (for example, the output ofsimple_func1("sq", |t| t*t)(symbol("x"))).add_symbolic– when the body is an already-builtE(e.g. fromparse::parse) and you don’t want to wrap it in a closure. Body is auto-differentiated.add_with_kind– escape hatch: name, parameter list, and a hand-builtFuncKinddirectly.
§Variable / parameter shadowing
Parameters declared when the function is registered always shadow variables of the same name in the caller’s eval context. For example, after:
let mut bag = FunctionBag::new();
bag.add_symbolic("sq", vec!["x".into()], parse("x*x").unwrap());
let e = parse_with_functions("sq(3)", &bag).unwrap();
let vars = [("x", 5.0)].into_iter().collect();
let r = e.eval(&vars).unwrap(); // 9.0, not 25.0the outer x = 5.0 is shadowed inside the function body by the
formal parameter x = 3.0 for the duration of the call.
§See also
examples/calc_demo.rs
is a bc-style REPL calculator built on top of FunctionBag +
parse::parse_with_functions: variables, runtime function
definitions (name(args) = expr), vars / funcs listings, and
readline-style history.
Implementations§
Source§impl FunctionBag
impl FunctionBag
Sourcepub fn new() -> Self
pub fn new() -> Self
Empty bag. Built-in functions remain available via the parser’s fallback lookup; only user-added functions go here.
Sourcepub fn add(&mut self, e: E) -> Result<(), String>
pub fn add(&mut self, e: E) -> Result<(), String>
Register a pre-built Expr::Func value. Use when you already
have an E (for example by calling one of the
simple_func1 / simple_func2 / simple_func /
extern_func1 / extern_func2 / extern_func
constructors on placeholder args).
For registering closures directly, use add1 /
add2 / addN.
Returns Err if e is not an Expr::Func.
Sourcepub fn add1<F>(&mut self, f: F) -> Result<(), String>
pub fn add1<F>(&mut self, f: F) -> Result<(), String>
Register a unary closure. The bag invokes it once with a
placeholder symbol to extract (name, params, kind).
bag.add1(simple_func1("sq", |t| t.clone() * t)).unwrap();Sourcepub fn add2<F>(&mut self, f: F) -> Result<(), String>
pub fn add2<F>(&mut self, f: F) -> Result<(), String>
Register a binary closure.
bag.add2(simple_func2("hypot",
|a, b| sqrt(a.clone()*a + b.clone()*b))).unwrap();Sourcepub fn addN<F>(&mut self, arity: usize, f: F) -> Result<(), String>
pub fn addN<F>(&mut self, arity: usize, f: F) -> Result<(), String>
Register an n-ary closure. Pairs with simple_func /
simple_func_derivs / extern_func for arities >= 3 and
for functions whose arity is known only at runtime. The
closure takes Vec<E> to match the shape those constructors
return (impl Fn(Vec<E>) -> E).
bag.addN(4, simple_func("blend", 4, |args: Vec<E>|
args[0].clone() + args[1].clone() + args[2].clone() + args[3].clone()
)).unwrap();Sourcepub fn add_symbolic(
&mut self,
name: impl Into<String>,
params: Vec<String>,
body: E,
)
pub fn add_symbolic( &mut self, name: impl Into<String>, params: Vec<String>, body: E, )
Convenience: register a symbolic function from an explicit
name, parameter list, and body E whose free symbols match
the params. Use this when you have the body as an already-built
expression (e.g. from parse) rather than as a closure.
Sourcepub fn add_with_kind(
&mut self,
name: impl Into<String>,
params: Vec<String>,
kind: FuncKind,
)
pub fn add_with_kind( &mut self, name: impl Into<String>, params: Vec<String>, kind: FuncKind, )
Direct form: register a function from name + parameters + kind.
Most callers should prefer add (closures / E)
or add_symbolic (parsed body) – this
is the escape hatch for building an unusual FuncKind by hand.
Sourcepub fn remove(&mut self, name: &str) -> bool
pub fn remove(&mut self, name: &str) -> bool
Remove a function by name. Returns true if it was present.
Does not affect built-ins.
Sourcepub fn contains(&self, name: &str) -> bool
pub fn contains(&self, name: &str) -> bool
Is this name registered in the bag? Does not consider built-ins.
Sourcepub fn names(&self) -> Vec<String>
pub fn names(&self) -> Vec<String>
Collect all names registered in the bag. Order is unspecified.
Sourcepub fn entries(&self) -> impl Iterator<Item = (&str, usize)>
pub fn entries(&self) -> impl Iterator<Item = (&str, usize)>
Iterate over (name, arity) pairs for every function in the
bag. Same data as names with arity attached.
Sourcepub fn get_info(&self, name: &str) -> Option<(&[String], &FuncKind)>
pub fn get_info(&self, name: &str) -> Option<(&[String], &FuncKind)>
Look up a function’s parameter names and kind. Returns None
if name isn’t in the bag. Useful for pretty-printing or
re-creating an Expr::Func outside the parser.
Sourcepub fn call(&self, name: &str, args: &[E]) -> Option<Result<E, String>>
pub fn call(&self, name: &str, args: &[E]) -> Option<Result<E, String>>
Build an Expr::Func by looking up name in this bag and
pairing it with args. Returns None if name is not
registered; returns Some(Err(..)) if the arity disagrees.
None means the name isn’t in the bag – callers that want
built-ins as a fallback should route through
parse::parse_with_functions or
function_by_name.
Trait Implementations§
Source§impl Clone for FunctionBag
impl Clone for FunctionBag
Source§fn clone(&self) -> FunctionBag
fn clone(&self) -> FunctionBag
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more