aboutsummaryrefslogtreecommitdiff
path: root/src/math/function.rs
blob: bd782f316328de7744b9e166a9bb3fa5e2880ee4 (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
67
68
use crate::math::{complex::Complex, context::Context};

pub struct FunctionArgument {
    args : Vec<Complex>,
}

impl FunctionArgument {
    pub fn new(args: Vec<Complex>) -> Self {
        Self { args }
    }

    pub fn get(&self, i : usize) -> Complex {
        self.args[i]
    }

    pub fn len(&self) -> usize {
        self.args.len()
    }

    pub fn is_empty(&self) -> bool {
        self.args.len() == 0
    }

    pub fn data(&self) -> &[Complex] {
        &self.args
    }
}

pub trait Function {
    fn eval(&self, args: FunctionArgument, ctx: &Context) -> Result<Complex, String>;
}

#[macro_export]
macro_rules! functions {
    {$($x:expr => $y:expr), *} => {
        {
            let mut h : HashMap<String, Arc<dyn Function>> = HashMap::new();
            $(
                h.insert($x.to_string(), Arc::new($y));
            )*
            h
        }
    };
}


// Some default implementations
impl<T> Function for T
where
    T: Fn(Complex) -> Complex,
{
    fn eval(&self, args: FunctionArgument, _ctx: &Context) -> Result<Complex, String> {
        if args.len() == 1 {
            Ok(self(args.get(0)))
        } else {
            Err("too many arguments".to_string())
        }
    }
}


pub struct EmptyFunction {}

impl Function for EmptyFunction {
    fn eval(&self, _args: FunctionArgument, _ctx: &Context) -> Result<Complex, String> {
        Err("function not implemented in this scope".to_string())
    }
}