Skip to main content

FunctionBag

Struct FunctionBag 

Source
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:

§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.0

the 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

Source

pub fn new() -> Self

Empty bag. Built-in functions remain available via the parser’s fallback lookup; only user-added functions go here.

Source

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.

Source

pub fn add1<F>(&mut self, f: F) -> Result<(), String>
where F: FnOnce(E) -> E,

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();
Source

pub fn add2<F>(&mut self, f: F) -> Result<(), String>
where F: FnOnce(E, E) -> E,

Register a binary closure.

bag.add2(simple_func2("hypot",
    |a, b| sqrt(a.clone()*a + b.clone()*b))).unwrap();
Source

pub fn addN<F>(&mut self, arity: usize, f: F) -> Result<(), String>
where F: FnOnce(Vec<E>) -> E,

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();
Source

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.

Source

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.

Source

pub fn remove(&mut self, name: &str) -> bool

Remove a function by name. Returns true if it was present. Does not affect built-ins.

Source

pub fn contains(&self, name: &str) -> bool

Is this name registered in the bag? Does not consider built-ins.

Source

pub fn names(&self) -> Vec<String>

Collect all names registered in the bag. Order is unspecified.

Source

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.

Source

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.

Source

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

Source§

fn clone(&self) -> FunctionBag

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Default for FunctionBag

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.