Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. use std::collections::HashMap;
  2. use std::fmt::Debug;
  3. use std::rc::Rc;
  4.  
  5. #[derive(Clone, Debug)]
  6. enum Value {
  7. Num(f64),
  8. }
  9.  
  10.  
  11. trait Expr: Debug + PartialEq {
  12. fn eval(&self, env: &HashMap<&'static str,Value>) -> Value;
  13. }
  14.  
  15. #[derive(Debug)]
  16. struct ExprSym(&'static str);
  17.  
  18. #[derive(Debug)]
  19. struct ExprNum(f64);
  20.  
  21. #[derive(Debug)]
  22. struct ExprAdd(Rc<Expr>,Rc<Expr>);
  23.  
  24.  
  25. impl Expr for ExprSym {
  26. fn eval(&self, env: &HashMap<&'static str,Value>) -> Value {
  27. env.get(&self.0).unwrap().clone()
  28. }
  29. }
  30.  
  31. impl Expr for ExprNum {
  32. fn eval(&self, _env: &HashMap<&'static str,Value>) -> Value {
  33. Value::Num(self.0)
  34. }
  35. }
  36.  
  37. impl Expr for ExprAdd {
  38. fn eval(&self, env: &HashMap<&'static str,Value>) -> Value {
  39. let lhs = self.0.eval(&env);
  40. let rhs = self.1.eval(&env);
  41. match (lhs, rhs) {
  42. (Value::Num(lhs), Value::Num(rhs)) => Value::Num(lhs+rhs),
  43. }
  44. }
  45. }
  46.  
  47.  
  48. fn main() {
  49. let mut env = HashMap::new();
  50. env.insert("a", Value::Num(1.0));
  51.  
  52. let a = Rc::new(ExprSym("a"));
  53. let b = Rc::new(ExprNum(2.0));
  54. let expr = ExprAdd(a, b);
  55. println!("{:?}", expr);
  56.  
  57. let result = expr.eval(&env);
  58. println!("{:?}", result);
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement