From 77cf9aa7535a1d9481f0bd3caeea26e2b85c5019 Mon Sep 17 00:00:00 2001 From: Nathan Reiner Date: Wed, 17 Jan 2024 22:30:02 +0100 Subject: migrate from f64 to own complex --- src/main.rs | 65 ++++++++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 45 insertions(+), 20 deletions(-) (limited to 'src/main.rs') 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 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> = 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), -- cgit v1.2.3-70-g09d2