Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::collections::HashMap;
- use std::fmt::Debug;
- use std::rc::Rc;
- #[derive(Clone, Debug)]
- enum Value {
- Num(f64),
- }
- trait Expr: Debug + PartialEq {
- fn eval(&self, env: &HashMap<&'static str,Value>) -> Value;
- }
- #[derive(Debug)]
- struct ExprSym(&'static str);
- #[derive(Debug)]
- struct ExprNum(f64);
- #[derive(Debug)]
- struct ExprAdd(Rc<Expr>,Rc<Expr>);
- impl Expr for ExprSym {
- fn eval(&self, env: &HashMap<&'static str,Value>) -> Value {
- env.get(&self.0).unwrap().clone()
- }
- }
- impl Expr for ExprNum {
- fn eval(&self, _env: &HashMap<&'static str,Value>) -> Value {
- Value::Num(self.0)
- }
- }
- impl Expr for ExprAdd {
- fn eval(&self, env: &HashMap<&'static str,Value>) -> Value {
- let lhs = self.0.eval(&env);
- let rhs = self.1.eval(&env);
- match (lhs, rhs) {
- (Value::Num(lhs), Value::Num(rhs)) => Value::Num(lhs+rhs),
- }
- }
- }
- fn main() {
- let mut env = HashMap::new();
- env.insert("a", Value::Num(1.0));
- let a = Rc::new(ExprSym("a"));
- let b = Rc::new(ExprNum(2.0));
- let expr = ExprAdd(a, b);
- println!("{:?}", expr);
- let result = expr.eval(&env);
- println!("{:?}", result);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement