Evaluate

Our Abstract Syntax Trees change the environment by evaluating themselves. In this chapter we see how that can be accomplished.

Nadezhda

We want our cockroach to evaluate her brain and change the environment accordingly. For this we introduce a trait Evaluator.

1 pub trait Evaluator {
2     fn evaluate_on(&self, environment: Environment) -> Environment;
3 }

If we would implement Evaluator for Program we could use it like.

1 let program: Program = forward!(forward!(forward!(stop!())));
2 let start: Environment = Environment::new(5);
3 
4 let finish: Environment = program.evaluate_on(start);

The implementation of Evaluator for Program directly reflects the structure of AST. For each encountered Forward we increment the cockroach position, for each encountered Backward we decrement the coackroach position and we stop when encountered Stop.

 1 impl Evaluator for Program {
 2     fn evaluate_on(&self, environment: Environment) -> Environment {
 3         match *self {
 4             Program::Forward(ref contained_program) => {
 5                 let next_environment =
 6                 Environment { cockroach_location : environment.cockroach_locatio\
 7 n + 1,
 8                   .. environment
 9                 };
10                 contained_program.evaluate_on(next_environment)
11             },
12             Program::Backward(ref contained_program) => {
13                 let next_environment =
14                 Environment { cockroach_location : environment.cockroach_locatio\
15 n - 1,
16                   .. environment
17                 };
18                 contained_program.evaluate_on(next_environment)
19             },
20             Program::Stop => {
21                 Environment { .. environment }
22             }
23         }
24     }
25 }