Variables and custom functions - Waigo01/math_utils_lib GitHub Wiki

The evaluator also allows for user defined variables and functions to be used during evaluation. Variables and functions can be defined using any name, as long as the name fulfills some rules (For more information on those rules, please take a look at docs.rs (Variable)). Note that the functions defined as operations take priority over user defined functions (although naming your function "sin" is valid, the operation "sin" will take priority).

Functions and Variables are bundled into a context. A corresponding code example would be:

let mut context = Context::default();
context.add_var(&Variable::new("x", value!()));

The Context::default() method can already add some variables to the context. These default variables are defined by the number type used (For more information, please take a look at docs.rs (Context)). Variables cand custom functions can also be assigned during evaluation. The quick_eval macro for example takes a mutable Context and one can assign variables using the Assing (=) operator:

let mut c = Context::default();

quick_eval!("f(x) = x^2", &mut c)?;

let res = quick_eval!("f(5)", &mut c)?.to_vec();

assert_eq!(res[0], value!(25));

Ok(())

While recursive function calls are not supported, side effects are. This means you can assign a new value to a variable outside of the function scope from inside the function. This allows for some interesting possibilities such as implementing a simple state machine:

let mut c = Context::empty();
quick_eval!("state = 0", &mut c)?;

// Using the power of lists, side effects in functions and if statements,
// we can even build simple state machines.

// This one recognizes the word 'math' with m = 0, a = 1, t = 2 and h = 3.

quick_eval!("f(x) =
if(x == 0 & state == 0,
   state = 1,
if(x == 1 & state == 1,
   state = 2,
if(x == 2 & state == 2,
   state = 3,
if(x == 3 & state == 3,
   state = 4,
state = 0))))", &mut c)?;

// This is the word 'math'.

quick_eval!("f({0, 1, 2, 3})", &mut c)?;

let res = quick_eval!("state", &mut c)?.to_vec();

assert_eq!(res[0], value!(4));

quick_eval!("state = 0", &mut c)?;

// This is NOT the word 'math'.

quick_eval!("f({0, 1, 4, 2})", &mut c)?.to_vec();

let res = quick_eval!("state", &mut c)?.to_vec();

assert_ne!(res[0], value!(4));
⚠️ **GitHub.com Fallback** ⚠️