Skip to content

Instantly share code, notes, and snippets.

@KGZM
Created October 2, 2013 03:08
Show Gist options
  • Save KGZM/6788603 to your computer and use it in GitHub Desktop.
Save KGZM/6788603 to your computer and use it in GitHub Desktop.
Just experimenting a bit.
enum Operation {
Add,
Sub,
Mul,
Div,
Exp
}
impl Operation {
fn apply(self, a : int, b : int) -> int {
match self {
Add => a + b,
Sub => a - b,
Mul => a * b,
Div => a / b,
Exp => a ^ b,
}
}
}
trait Expression : Send{
fn eval(&self) -> int;
}
struct Number(int);
impl Expression for Number {
fn eval(&self) -> int {
match *self {
Number(a) => a
}
}
}
struct BinaryOperatorExpression {
operation : Operation,
lhs : ~Expression,
rhs : ~Expression,
}
impl Expression for BinaryOperatorExpression {
fn eval(&self) -> int {
self.operation.apply(self.lhs.eval(), self.rhs.eval())
}
}
fn main() {
let exp = BinaryOperatorExpression {
operation: Add,
lhs: ~Number(5) as ~Expression,
rhs: ~BinaryOperatorExpression {
operation: Sub,
lhs: ~Number(2) as ~Expression,
rhs: ~Number(3) as ~Expression
} as ~Expression
};
println!("{:?}", exp.eval());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment