Week 13: Exercises

1. Automatic Type Conversion

Enhance the P2 interpreter we wrote in class to perform automatic type conversions between integers and booleans:

2. Boolean Operators

Suppose that we would like to add the boolean operators && (AND) and || (OR) to the P2 interpreter that we wrote in class.

a) Should these operators have the same precedence? What should their precedence be relative to the other operators that P2 already supports?

b) Enhance the P2 grammar to include these operators.

c) Enhance the P2 parser to handle these operators.

d) Enhance the P2 interpreter to handle these operators.

3. Not

As an extension to the previous exercise, add the ! (NOT) operator to the P2 interpreter. This is a unary operator, unlike all other existing operators which are binary, so you will need to extend the grammar and abstract syntax accordingly.

4. Static Type Checking

Assuming that we have not implemented the automatic type conversions from a previous exercise, a P2 program might produce an error at run time, for example if we try to add two values, one of which is the Boolean constant false.

Enhance the P2 interpreter so that it performs static type checking: before a program starts to run, the interpreter should verify that all the operations in the program are type-correct.

5. Polynomial Time

A P2 program cannot read input, so every time you run a P2 program you will get the same result.

Let T(N) be the maximum time for running any P2 program whose length is N characters. Is T(N) a polynomial function of N? If so, prove it. If not, describe how to write a series of P2 programs whose running times increase non-polynomially (e.g. exponentially) in the length of the programs.