From 1713618d4cc0194674f91fd2d24ef2de88f21784 Mon Sep 17 00:00:00 2001 From: Nathan Reiner Date: Thu, 18 Jan 2024 18:29:10 +0100 Subject: create small iced demo --- src/math/expression_function.rs | 60 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 src/math/expression_function.rs (limited to 'src/math/expression_function.rs') diff --git a/src/math/expression_function.rs b/src/math/expression_function.rs new file mode 100644 index 0000000..20f4816 --- /dev/null +++ b/src/math/expression_function.rs @@ -0,0 +1,60 @@ +use std::iter::zip; +use std::sync::Arc; + +use crate::math::{ + complex::Complex, + context::Context, + expression::Expression, + function::{Function, FunctionArgument, EmptyFunction} +}; + +#[derive(Default)] +pub struct ExpressionFunction { + expr: Expression, + name: String, + args: Vec, +} + +impl ExpressionFunction { + pub fn from_string(str: String) -> Self { + let str = str.replace(' ', ""); + let (lhs, expr) = str.split_once('=').unwrap(); + let (name, a) = lhs.split_once('(').unwrap(); + let args: Vec = a[0..a.len() - 1] + .split(',') + .map(|s| s.to_string()) + .collect(); + Self { + expr: Expression::from_string(expr), + name: name.to_string(), + args, + } + } + + pub fn name(&self) -> &str { + &self.name + } + + pub fn content(&self) -> &str { + &self.expr.content() + } +} + +impl Function for ExpressionFunction { + fn eval(&self, args: FunctionArgument, ctx: &Context) -> Result { + if args.len() == self.args.len() { + let mut nctx = ctx.clone(); + for (n, v) in zip(self.args.iter(), args.data().iter()) { + nctx.set_variable(n, *v) + } + nctx.set_function(self.name(), Arc::new(EmptyFunction {})); + self.expr.evaluate(&nctx) + } else { + Err(format!( + "{} takes {} parameters", + self.name, + self.args.len() + )) + } + } +} -- cgit v1.2.3-70-g09d2