Trait meval::ContextProvider [] [src]

pub trait ContextProvider {
    fn get_var(&self, _: &str) -> Option<f64> { ... }
    fn eval_func(&self, _: &str, _: &[f64]) -> Result<f64, FuncEvalError> { ... }
}

A trait of a source of variables (and constants) and functions for substitution into an evaluated expression.

A simplest way to create a custom context provider is to use Context.

Advanced usage

Alternatively, values of variables/constants can be specified by tuples (name, value), std::collections::HashMap or std::collections::BTreeMap.

use meval::{ContextProvider, Context};

let mut ctx = Context::new(); // built-ins
ctx.var("x", 2.); // insert a new variable
assert_eq!(ctx.get_var("pi"), Some(std::f64::consts::PI));

let myvars = ("x", 2.); // tuple as a ContextProvider
assert_eq!(myvars.get_var("x"), Some(2f64));

// HashMap as a ContextProvider
let mut varmap = std::collections::HashMap::new();
varmap.insert("x", 2.);
varmap.insert("y", 3.);
assert_eq!(varmap.get_var("x"), Some(2f64));
assert_eq!(varmap.get_var("z"), None);

Custom functions can be also defined.

use meval::{ContextProvider, Context};

let mut ctx = Context::new(); // built-ins
ctx.func2("phi", |x, y| x / (y * y));

assert_eq!(ctx.eval_func("phi", &[2., 3.]), Ok(2. / (3. * 3.)));

A ContextProvider can be built by combining other contexts:

use meval::Context;

let bins = Context::new(); // built-ins
let mut funcs = Context::empty(); // empty context
funcs.func2("phi", |x, y| x / (y * y));
let myvars = ("x", 2.);

// contexts can be combined using tuples
let ctx = ((myvars, bins), funcs); // first context has preference if there's duplicity

assert_eq!(meval::eval_str_with_context("x * pi + phi(1., 2.)", ctx).unwrap(), 2. *
            std::f64::consts::PI + 1. / (2. * 2.));

Provided Methods

Implementors