use std::{collections::HashMap, iter::zip}; use crate::{ commonsense_functions, commonsense_operations, functions, complex::Complex, context::Context, expression::Expression, operation::Operation, function::{Function, FunctionArgument} }; 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(',') .into_iter() .map(|s| s.to_string()) .collect(); Self { expr: Expression::from_string(expr), name: name.to_string(), args, } } pub fn name(&self) -> &str { &self.name } } impl Function for ExpressionFunction { fn eval(&self, args: FunctionArgument) -> Result { if args.len() == self.args.len() { let mut vars = HashMap::new(); for (n, v) in zip(self.args.iter(), args.data().iter()) { vars.insert(n.to_string(), v.clone()); } let ctx = Context::new() .with_variables(vars) .with_functions(commonsense_functions! {}) .with_operations(commonsense_operations! {}); self.expr.evaluate(&ctx) } else { Err(format!( "{} takes {} parameters", self.name, self.args.len() )) } } }