Type Systems, Exc. 1 Arithmetic expressions |
|||||
English only |
|||||
This page has been updated with sections Errata and Solution.
Exercise 1 Arithmetic ExpressionsIn this exercise, you are asked to familiarize yourself with Scala by implementing an evaluator for arithmetic expressions. The grammar of expressions is repeated here (production E). An expression is sometimes also called term. Some terms are called values(prod. V) and of these, some are numeric values (prod. NV).
An evaluation means reducing terms until they are no longer reducible. If all goes well, the result is a value. If it is not a value, then evaluation is stuck. The behaviour of an evaluator can be described concisely by writing deduction rules of the form
Such a rule says, that if all premises hold, than the conclusion holds. If there is just a conclusion and no premises, then the line is omitted. Here, we are interested in the reduction relation →. It is a binary relation on terms, where "a → b" says than we can reduce a to b. The reduction relation for arithmetic expressions was given in the course . Let's repeat them here:
The meta variables Preparation
Task 1.1Write an evaluator that reduces terms according the reduction relation.
Start by completing method scala arithexpr.Main -print test/test1.expr This does not run the evaluator.
Then proceed to the methods in Task 1.2Give one term whose evaluation gets stuck (which does not reduce to a value). ErrataPlease note this error inEvaluatorPhase.scala
/** evaluates an expression */ def apply(t: Expr): Expr = { val s = eval(t); if(!isVal(s)) { // instead of !isVal(t) Console.println("Evaluation is stuck."); } s }This is a good example of an programming error that no type system will find :-/. SolutionHere are the complete files Expr.scala and EvaluatorPhase.scala.RemarksThe implementation of the exercise yields an interpreter that is not very efficient. However, it is easy to see that it corresponds exactly to the definition of the reduction relation. It can be seen that congruence rules are just there to recursively
search for redexes. The only interesting thing about congruence rules
is, where they lead the search for redexes. Note that a premise
In the given framework, |
|