aboutsummaryrefslogtreecommitdiff
path: root/src/math/expression_function.rs
blob: 9debdc4864328881e01a66432fa563b01bceda7d (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
61
62
63
64
65
66
use std::iter::zip;
use std::sync::Arc;

use crate::math::{
    complex::Complex,
    context::Context,
    expression::Expression,
    operation::Operation,
    function::{Function, FunctionArgument, EmptyFunction}
};

#[derive(Default, Clone)]
pub struct ExpressionFunction {
    expr: Expression,
    name: String,
    args: Vec<String>,
}

impl ExpressionFunction {
    pub fn from_string(str: String, operations: &Vec<Operation>) -> Result<Self, ()> {
        let str = str.replace(' ', "");
        if let Some((lhs, expr)) = str.split_once('=') {
            if let Some((name, a)) = lhs.split_once('(') {
                let args: Vec<String> = a[0..a.len() - 1]
                    .split(',')
                    .map(|s| s.to_string())
                    .collect();

                return Ok(Self {
                    expr: Expression::from_string(expr, operations),
                    name: name.to_string(),
                    args,
                })
            }
        }
        Err(())
    }

    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<Complex, String> {
        if args.len() == self.args.len() {
            let mut nctx = ctx.clone();
            let vargs = args.eval_args(ctx)?;
            for (n, v) in zip(self.args.iter(), vargs.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()
            ))
        }
    }
}