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
|
pub mod complex;
pub mod context;
pub mod expression;
pub mod function;
pub mod operation;
pub mod string;
use std::collections::HashMap;
use complex::Complex;
use context::Context;
use expression::Expression;
use function::Function;
use operation::Operation;
fn add(a: Complex, b: Complex) -> Complex {
a + b
}
fn sub(a: Complex, b: Complex) -> Complex {
a - b
}
fn mul(a: Complex, b: Complex) -> Complex {
a * b
}
fn div(a: Complex, b: Complex) -> Complex {
a / b
}
fn pow(a: Complex, b: Complex) -> Complex {
a.pow(b)
}
fn sqrt(a: Complex) -> Complex {
a.sqrt()
}
fn sin(a: Complex) -> Complex {
a.sin()
}
fn cos(a: Complex) -> Complex {
a.cos()
}
fn tan(a: Complex) -> Complex {
a.tan()
}
fn main() {
let expr = "cos(3)";
let ctx: Context = Context::new()
.with_operations(operations![{
'+' => &add,
'-' => &sub,
'*' => &mul,
'/' => &div,
'^' => &pow
}])
.with_functions(functions!({"sqrt" => &sqrt, "sin" => &sin, "cos" => &cos, "tan" => &tan}))
.with_variables(variables!({"x" => Complex::new(5.0, 0.0)}));
let value = Expression::from_string(expr);
match value.evaluate(&ctx) {
Ok(res) => println!("{} = {}", expr, res),
Err(err) => println!("Error: {}", err),
}
let value = Expression::from_string("sin(3)");
match value.evaluate(&ctx) {
Ok(res) => println!("{} = {}", expr, res),
Err(err) => println!("Error: {}", err),
}
let value = Expression::from_string("tan(3)");
match value.evaluate(&ctx) {
Ok(res) => println!("{} = {}", expr, res),
Err(err) => println!("Error: {}", err),
}
}
|