Skip to content

Instantly share code, notes, and snippets.

@huyng
Last active November 4, 2016 15:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huyng/65a88779684b3e6fa9e9 to your computer and use it in GitHub Desktop.
Save huyng/65a88779684b3e6fa9e9 to your computer and use it in GitHub Desktop.
Rust symbolic algebra system
enum Node {
TVector(&'static str),
TScalar(f32),
Add(Box<Node>, Box<Node>),
Sub(Box<Node>, Box<Node>),
Mul(Box<Node>, Box<Node>),
Div(Box<Node>, Box<Node>),
Pow(Box<Node>, Box<Node>),
}
impl Node {
fn eval(&self) {
match *self {
TVector(a) => {
println!("TVector({})", a);
},
TScalar(a) => {
println!("TScalar({})", a);
},
Add(ref a, ref b) => {
println!("Add");
a.eval();
b.eval();
},
Sub(ref a, ref b) => {
println!("Sub");
a.eval();
b.eval();
},
Mul(ref a, ref b) => {
println!("Mul")
a.eval();
b.eval();
},
Div(ref a, ref b) => {
println!("Div");
a.eval();
b.eval();
},
Pow(ref a, ref b) => {
println!("Pow");
a.eval();
b.eval();
}
}
}
}
fn main() {
// f(x) = 5.2 - 1/(1 + e^-x)
let f = Sub(box TScalar(5.2),
box Div(
box TScalar(1.0),
box Add(
box TScalar(1.0),
box Pow(
box TScalar(2.1718),
box Mul(
box TScalar(-1.0),
box TVector("x"))))));
f.eval();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment