aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
diff options
context:
space:
mode:
authorNathan Reiner <nathan@nathanreiner.xyz>2024-01-17 22:30:02 +0100
committerNathan Reiner <nathan@nathanreiner.xyz>2024-01-17 22:30:02 +0100
commit77cf9aa7535a1d9481f0bd3caeea26e2b85c5019 (patch)
tree03b794cc47e14da1d3896c4251c89fa6c40a7132 /src/main.rs
parent5ccc6e5ec8a433f68bfeb17e8dcedec5b62a36a9 (diff)
migrate from f64 to own complex
Diffstat (limited to 'src/main.rs')
-rw-r--r--src/main.rs65
1 files changed, 45 insertions, 20 deletions
diff --git a/src/main.rs b/src/main.rs
index 313769f..d1e914d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,3 +1,4 @@
+pub mod complex;
pub mod context;
pub mod expression;
pub mod function;
@@ -6,51 +7,75 @@ pub mod string;
use std::collections::HashMap;
+use complex::Complex;
+use context::Context;
use expression::Expression;
use function::Function;
use operation::Operation;
-use crate::context::Context;
-
-fn add(a: f64, b: f64) -> f64 {
+fn add(a: Complex, b: Complex) -> Complex {
a + b
}
-fn mul(a: f64, b: f64) -> f64 {
+fn sub(a: Complex, b: Complex) -> Complex {
+ a - b
+}
+
+fn mul(a: Complex, b: Complex) -> Complex {
a * b
}
-fn div(a: f64, b: f64) -> f64 {
+fn div(a: Complex, b: Complex) -> Complex {
a / b
}
-fn pow(a: f64, b: f64) -> f64 {
- a.powf(b)
+fn pow(a: Complex, b: Complex) -> Complex {
+ a.pow(b)
}
-fn sqrt(a: f64) -> f64 {
+fn sqrt(a: Complex) -> Complex {
a.sqrt()
}
-impl<T> Function for T
-where
- T: Fn(f64) -> f64,
-{
- fn eval(&self, args: function::FunctionArgument) -> f64 {
- self(args.get(0))
- }
+fn sin(a: Complex) -> Complex {
+ a.sin()
+}
+
+fn cos(a: Complex) -> Complex {
+ a.cos()
+}
+
+fn tan(a: Complex) -> Complex {
+ a.tan()
}
fn main() {
- let expr = "(2 + (3 + 10) * (3 + 10)) * 2";
+ let expr = "cos(3)";
- 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);
+ .with_operations(operations![{
+ '+' => &add,
+ '-' => &sub,
+ '*' => &mul,
+ '/' => &div,
+ '^' => &pow
+ }])
+ .with_functions(functions!({"sqrt" => &sqrt, "sin" => &sin, "cos" => &cos, "tan" => &tan}))
+ .with_variables(variables!({"x" => Complex::new(5.0, 0.0)}));
+
let value = Expression::from_string(expr);
+ match value.evaluate(&ctx) {
+ Ok(res) => println!("{} = {}", expr, res),
+ Err(err) => println!("Error: {}", err),
+ }
+
+ let value = Expression::from_string("sin(3)");
+ match value.evaluate(&ctx) {
+ Ok(res) => println!("{} = {}", expr, res),
+ Err(err) => println!("Error: {}", err),
+ }
+ let value = Expression::from_string("tan(3)");
match value.evaluate(&ctx) {
Ok(res) => println!("{} = {}", expr, res),
Err(err) => println!("Error: {}", err),