aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/main.rs')
-rw-r--r--src/main.rs58
1 files changed, 58 insertions, 0 deletions
diff --git a/src/main.rs b/src/main.rs
new file mode 100644
index 0000000..313769f
--- /dev/null
+++ b/src/main.rs
@@ -0,0 +1,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),
+ }
+}