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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
use super::expression::Expression;
use super::{complex::Complex, context::Context};
#[derive(PartialEq, Eq, Hash, Clone)]
enum FunctionArgumentType {
ExpressionArgument(Vec<Expression>),
ValueArgument(Vec<Complex>),
}
#[derive(PartialEq, Eq, Hash, Clone)]
pub struct FunctionArgument {
args: FunctionArgumentType,
len: usize,
}
impl FunctionArgument {
pub fn from_expressions(args: Vec<Expression>) -> Self {
Self {
len: args.len(),
args: FunctionArgumentType::ExpressionArgument(args),
}
}
pub fn from_values(args: Vec<Complex>) -> Self {
Self {
len: args.len(),
args: FunctionArgumentType::ValueArgument(args),
}
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn eval_args(&self, ctx: &Context) -> Result<Vec<Complex>, String> {
match &self.args {
FunctionArgumentType::ExpressionArgument(args) => {
args.iter().map(|a| a.evaluate(ctx)).collect()
}
FunctionArgumentType::ValueArgument(args) => Ok(args.to_vec()),
}
}
}
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 {
match args.eval_args(ctx) {
Ok(args) => Ok(self(args[0])),
Err(e) => Err(e),
}
} 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())
}
}
|