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
use crate::Expression;
fn f64_to_string_with_precision(v: f64) -> String {
let v_str = v.to_string();
if v_str.contains('.') {
v_str
} else {
v_str + ".0"
}
}
impl Expression {
pub(crate) fn _rust_code(&self, parentheses: bool) -> String {
match self {
Expression::Symbol(symbol) => Expression::rust_code_symbol(symbol),
Expression::Constant(v) => f64_to_string_with_precision(*v),
Expression::Add(l, r) => Expression::rust_code_add(l, r, parentheses),
Expression::Sub(l, r) => Expression::rust_code_sub(l, r, parentheses),
Expression::Mul(l, r) => Expression::rust_code_mul(l, r, parentheses),
Expression::Div(l, r) => Expression::rust_code_div(l, r, parentheses),
Expression::Neg(v) => Expression::rust_code_neg(v),
Expression::Pow(base, exponent) => Expression::rust_code_powr(base, exponent),
Expression::Transcendental(v) => v.rust_code(),
Expression::DegeneratedTensor(v) => v._rust_code(parentheses),
Expression::DiffResultTensor(v) => v._rust_code(parentheses),
}
}
pub fn rust_code(&self) -> String {
Self::_rust_code(&self, false)
}
}
#[cfg(test)]
mod tests {
use crate::*;
#[test]
fn it_works() {
let x = new_symbol("x".to_string());
let expression = x.clone().powr(2.into());
println!("{}", expression.rust_code());
}
#[test]
fn it_works2() {
let x = new_symbol("x".to_string());
let expression = (2.0 * x.clone()).exp();
println!("{}", expression.rust_code());
}
#[test]
fn it_works3() {
let x = new_symbol("x".to_string());
let expression = x.clone().sin() + x.clone().cos().exp();
println!("{}", expression.rust_code());
}
#[test]
fn it_works4() {
let x = new_symbol("x".to_string());
let expression = x.clone().powr(2.into());
println!("{}", expression.rust_code());
}
}