Created
October 2, 2013 03:08
-
-
Save KGZM/6788603 to your computer and use it in GitHub Desktop.
Just experimenting a bit.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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