pub struct Expression<N: Num> {
pub string: String,
pub ctx: Context<N>,
pub term: Term<N>,
}Expand description
The main Expression struct. Contains the string that was originally requested to be parsed, the context the Expression was parsed with, and the Term the raw form was parsed as. For just the parsed version of the expression, use the Term enum.
Fields§
§string: StringThe original string passed into this expression
ctx: Context<N>Context the expression was parsed with
term: Term<N>The term this string has been parsed as
Implementations§
Source§impl<N: Num + 'static> Expression<N>
impl<N: Num + 'static> Expression<N>
Sourcepub fn parse(raw: &str) -> Result<Self, ParseError>
pub fn parse(raw: &str) -> Result<Self, ParseError>
Parse a string into an expression
Examples found in repository?
examples/basic.rs (line 19)
10fn main() {
11 println!("MEXPRP Test Calculator\n---------------------");
12 loop {
13 let mut buf = String::new();
14 print!("> ");
15 io::stdout().flush().unwrap();
16 io::stdin().read_line(&mut buf).unwrap();
17
18 // Parse the expression (with the default context)
19 let expr: Expression<f64> = match Expression::parse(&buf) {
20 Ok(expr) => expr,
21 Err(e) => {
22 println!("Failed to parse expression: {}", e);
23 continue;
24 }
25 };
26
27 // Evaluate the expression or print the error if there was one
28 match expr.eval() {
29 Ok(val) => println!("\t= {}", val),
30 Err(e) => println!("Failed to evaluate the expression: {}", e),
31 }
32 }
33}Sourcepub fn parse_ctx(raw: &str, ctx: Context<N>) -> Result<Self, ParseError>
pub fn parse_ctx(raw: &str, ctx: Context<N>) -> Result<Self, ParseError>
Parse a string into an expression with the given context
Examples found in repository?
examples/context.rs (line 39)
8fn main() {
9 // A context holds data that can be used in an expression
10 let mut context: Context<f64> = Context::new();
11 // Add a variable "x" to the context with the value 5.4
12 context.set_var("x", 5.4);
13 // Add a function "sum" to the context that returns the sum of it's arguments. A closure is passed
14 // in that takes twp arguments: args: &[Term], which is a slice if the arguments passed into the
15 // function, and ctx: &Context, which is a reference to the context which the expression is being
16 // evaluated with. The item passed in can be anything that implements the `Func` trait. There exists
17 // a blanket impl for Fn(&[Term], &Context) -> Calculation which allows you to pass in closures in
18 // that format.
19 context.set_func(
20 "sum",
21 |args: &[Term<f64>], ctx: &Context<f64>| -> Calculation<f64> {
22 if args.len() < 1 {
23 return Err(MathError::IncorrectArguments);
24 };
25
26 let mut sum = Answer::Single(0.0);
27 for arg in args {
28 let b = arg.eval_ctx(ctx)?;
29 sum = sum.op(&b, |a, b| Num::add(a, b, ctx))?;
30 }
31
32 Ok(sum)
33 },
34 );
35
36 let raw = "2 * sum(x, 7, 400)";
37 // The expression needs to be parsed with the context in order do decide if some names are functions
38 // or variables.
39 let expr = Expression::parse_ctx(raw, context).unwrap();
40 // The expression also needs to be evaluated with a context. This context can be different than the
41 // one it was parsed with, but if it is missing something that is necessary for evaluation the
42 // evaluation will fail.
43 println!("{} = {}", raw, expr.eval().unwrap())
44}Sourcepub fn eval(&self) -> Calculation<N>
pub fn eval(&self) -> Calculation<N>
Evaluate the expression
Examples found in repository?
examples/basic.rs (line 28)
10fn main() {
11 println!("MEXPRP Test Calculator\n---------------------");
12 loop {
13 let mut buf = String::new();
14 print!("> ");
15 io::stdout().flush().unwrap();
16 io::stdin().read_line(&mut buf).unwrap();
17
18 // Parse the expression (with the default context)
19 let expr: Expression<f64> = match Expression::parse(&buf) {
20 Ok(expr) => expr,
21 Err(e) => {
22 println!("Failed to parse expression: {}", e);
23 continue;
24 }
25 };
26
27 // Evaluate the expression or print the error if there was one
28 match expr.eval() {
29 Ok(val) => println!("\t= {}", val),
30 Err(e) => println!("Failed to evaluate the expression: {}", e),
31 }
32 }
33}More examples
examples/context.rs (line 43)
8fn main() {
9 // A context holds data that can be used in an expression
10 let mut context: Context<f64> = Context::new();
11 // Add a variable "x" to the context with the value 5.4
12 context.set_var("x", 5.4);
13 // Add a function "sum" to the context that returns the sum of it's arguments. A closure is passed
14 // in that takes twp arguments: args: &[Term], which is a slice if the arguments passed into the
15 // function, and ctx: &Context, which is a reference to the context which the expression is being
16 // evaluated with. The item passed in can be anything that implements the `Func` trait. There exists
17 // a blanket impl for Fn(&[Term], &Context) -> Calculation which allows you to pass in closures in
18 // that format.
19 context.set_func(
20 "sum",
21 |args: &[Term<f64>], ctx: &Context<f64>| -> Calculation<f64> {
22 if args.len() < 1 {
23 return Err(MathError::IncorrectArguments);
24 };
25
26 let mut sum = Answer::Single(0.0);
27 for arg in args {
28 let b = arg.eval_ctx(ctx)?;
29 sum = sum.op(&b, |a, b| Num::add(a, b, ctx))?;
30 }
31
32 Ok(sum)
33 },
34 );
35
36 let raw = "2 * sum(x, 7, 400)";
37 // The expression needs to be parsed with the context in order do decide if some names are functions
38 // or variables.
39 let expr = Expression::parse_ctx(raw, context).unwrap();
40 // The expression also needs to be evaluated with a context. This context can be different than the
41 // one it was parsed with, but if it is missing something that is necessary for evaluation the
42 // evaluation will fail.
43 println!("{} = {}", raw, expr.eval().unwrap())
44}Sourcepub fn eval_ctx(&self, ctx: &Context<N>) -> Calculation<N>
pub fn eval_ctx(&self, ctx: &Context<N>) -> Calculation<N>
Evaluate the expression with the given context
Trait Implementations§
Source§impl<N: Clone + Num> Clone for Expression<N>
impl<N: Clone + Num> Clone for Expression<N>
Source§fn clone(&self) -> Expression<N>
fn clone(&self) -> Expression<N>
Returns a duplicate of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moreSource§impl<N: Num> Display for Expression<N>
impl<N: Num> Display for Expression<N>
Auto Trait Implementations§
impl<N> Freeze for Expression<N>where
N: Freeze,
impl<N> !RefUnwindSafe for Expression<N>
impl<N> !Send for Expression<N>
impl<N> !Sync for Expression<N>
impl<N> Unpin for Expression<N>where
N: Unpin,
impl<N> !UnwindSafe for Expression<N>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> CheckedAs for T
impl<T> CheckedAs for T
Source§fn checked_as<Dst>(self) -> Option<Dst>where
T: CheckedCast<Dst>,
fn checked_as<Dst>(self) -> Option<Dst>where
T: CheckedCast<Dst>,
Casts the value.
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> OverflowingAs for T
impl<T> OverflowingAs for T
Source§fn overflowing_as<Dst>(self) -> (Dst, bool)where
T: OverflowingCast<Dst>,
fn overflowing_as<Dst>(self) -> (Dst, bool)where
T: OverflowingCast<Dst>,
Casts the value.
Source§impl<T> SaturatingAs for T
impl<T> SaturatingAs for T
Source§fn saturating_as<Dst>(self) -> Dstwhere
T: SaturatingCast<Dst>,
fn saturating_as<Dst>(self) -> Dstwhere
T: SaturatingCast<Dst>,
Casts the value.
Source§impl<T> UnwrappedAs for T
impl<T> UnwrappedAs for T
Source§fn unwrapped_as<Dst>(self) -> Dstwhere
T: UnwrappedCast<Dst>,
fn unwrapped_as<Dst>(self) -> Dstwhere
T: UnwrappedCast<Dst>,
Casts the value.
Source§impl<T> WrappingAs for T
impl<T> WrappingAs for T
Source§fn wrapping_as<Dst>(self) -> Dstwhere
T: WrappingCast<Dst>,
fn wrapping_as<Dst>(self) -> Dstwhere
T: WrappingCast<Dst>,
Casts the value.