1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
pub mod context;
pub mod expression;
pub mod function;
pub mod operation;
pub mod string;
use std::collections::HashMap;
use expression::Expression;
use function::Function;
use operation::Operation;
use crate::context::Context;
fn add(a: f64, b: f64) -> f64 {
a + b
}
fn mul(a: f64, b: f64) -> f64 {
a * b
}
fn div(a: f64, b: f64) -> f64 {
a / b
}
fn pow(a: f64, b: f64) -> f64 {
a.powf(b)
}
fn sqrt(a: f64) -> f64 {
a.sqrt()
}
impl<T> Function for T
where
T: Fn(f64) -> f64,
{
fn eval(&self, args: function::FunctionArgument) -> f64 {
self(args.get(0))
}
}
fn main() {
let expr = "(2 + (3 + 10) * (3 + 10)) * 2";
let mut funcs : HashMap<String, Box<dyn Function>> = HashMap::new();
funcs.insert("sqrt".to_string(), Box::new(&sqrt));
let ctx: Context = Context::new()
.with_operations(opvec![('+', &add), ('*', &mul), ('/', &div), ('^', &pow)])
.with_functions(funcs);
let value = Expression::from_string(expr);
match value.evaluate(&ctx) {
Ok(res) => println!("{} = {}", expr, res),
Err(err) => println!("Error: {}", err),
}
}
|