aboutsummaryrefslogtreecommitdiff
path: root/src/expression_function.rs
blob: 35eba5fc81f924dc53681886416910a5fad9b579 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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<String>,
}

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<String> = 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<Complex, String> {
        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()
            ))
        }
    }
}