Exercise: Expression Evaluation

Let’s write a simple recursive evaluator for arithmetic expressions.

An example of a small arithmetic expression could be 10 + 20, which evaluates to 30. We can represent the expression as a tree:

12.5. Exercise: Expression Evaluation - 图1

A bigger and more complex expression would be (10 * 9) + ((3 - 4) * 5), which evaluate to 85. We represent this as a much bigger tree:

12.5. Exercise: Expression Evaluation - 图2

In code, we will represent the tree with two types:

  1. #![allow(unused)]
  2. fn main() {
  3. /// An operation to perform on two subexpressions.
  4. #[derive(Debug)]
  5. enum Operation {
  6.     Add,
  7.     Sub,
  8.     Mul,
  9.     Div,
  10. }
  11. /// An expression, in tree form.
  12. #[derive(Debug)]
  13. enum Expression {
  14.     /// An operation on two subexpressions.
  15.     Op { op: Operation, left: Box<Expression>, right: Box<Expression> },
  16.     /// A literal value
  17.     Value(i64),
  18. }
  19. }

The Box type here is a smart pointer, and will be covered in detail later in the course. An expression can be “boxed” with Box::new as seen in the tests. To evaluate a boxed expression, use the deref operator (*) to “unbox” it: eval(*boxed_expr).

Some expressions cannot be evaluated and will return an error. The standard Result type is an enum that represents either a successful value (Ok(Value)) or an error (Err(String)). We will cover this type in detail later.

Copy and paste the code into the Rust playground, and begin implementing eval. The final product should pass the tests. It may be helpful to use todo!() and get the tests to pass one-by-one. You can also skip a test temporarily with #[ignore]:

  1. #[test]
  2. #[ignore]
  3. fn test_value() { .. }
  1. #![allow(unused)]
  2. fn main() {
  3. /// An operation to perform on two subexpressions.
  4. #[derive(Debug)]
  5. enum Operation {
  6.     Add,
  7.     Sub,
  8.     Mul,
  9.     Div,
  10. }
  11. /// An expression, in tree form.
  12. #[derive(Debug)]
  13. enum Expression {
  14.     /// An operation on two subexpressions.
  15.     Op { op: Operation, left: Box<Expression>, right: Box<Expression> },
  16.     /// A literal value
  17.     Value(i64),
  18. }
  19. fn eval(e: Expression) -> Result<i64, String> {
  20.     todo!()
  21. }
  22. #[test]
  23. fn test_value() {
  24.     assert_eq!(eval(Expression::Value(19)), Ok(19));
  25. }
  26. #[test]
  27. fn test_sum() {
  28.     assert_eq!(
  29.         eval(Expression::Op {
  30.             op: Operation::Add,
  31.             left: Box::new(Expression::Value(10)),
  32.             right: Box::new(Expression::Value(20)),
  33.         }),
  34.         Ok(30)
  35.     );
  36. }
  37. #[test]
  38. fn test_recursion() {
  39.     let term1 = Expression::Op {
  40.         op: Operation::Mul,
  41.         left: Box::new(Expression::Value(10)),
  42.         right: Box::new(Expression::Value(9)),
  43.     };
  44.     let term2 = Expression::Op {
  45.         op: Operation::Mul,
  46.         left: Box::new(Expression::Op {
  47.             op: Operation::Sub,
  48.             left: Box::new(Expression::Value(3)),
  49.             right: Box::new(Expression::Value(4)),
  50.         }),
  51.         right: Box::new(Expression::Value(5)),
  52.     };
  53.     assert_eq!(
  54.         eval(Expression::Op {
  55.             op: Operation::Add,
  56.             left: Box::new(term1),
  57.             right: Box::new(term2),
  58.         }),
  59.         Ok(85)
  60.     );
  61. }
  62. #[test]
  63. fn test_zeros() {
  64.     assert_eq!(
  65.         eval(Expression::Op {
  66.             op: Operation::Add,
  67.             left: Box::new(Expression::Value(0)),
  68.             right: Box::new(Expression::Value(0))
  69.         }),
  70.         Ok(0)
  71.     );
  72.     assert_eq!(
  73.         eval(Expression::Op {
  74.             op: Operation::Mul,
  75.             left: Box::new(Expression::Value(0)),
  76.             right: Box::new(Expression::Value(0))
  77.         }),
  78.         Ok(0)
  79.     );
  80.     assert_eq!(
  81.         eval(Expression::Op {
  82.             op: Operation::Sub,
  83.             left: Box::new(Expression::Value(0)),
  84.             right: Box::new(Expression::Value(0))
  85.         }),
  86.         Ok(0)
  87.     );
  88. }
  89. #[test]
  90. fn test_error() {
  91.     assert_eq!(
  92.         eval(Expression::Op {
  93.             op: Operation::Div,
  94.             left: Box::new(Expression::Value(99)),
  95.             right: Box::new(Expression::Value(0)),
  96.         }),
  97.         Err(String::from("division by zero"))
  98.     );
  99. }
  100. }