Previous Contents Next

Exercises

Filtering Comments Out

Comments in Objective CAML are hierarchical. We can thus comment away sections of text, including those containing comments. A comment starts with characters (* and finishes with *). Here's an example:

(* comment spread
over several
lines *)

let succ x = (* successor function *)
x + 1;;

(* level 1 commented text
let old_succ y = (* level 2 successor function level 2 *)
y +1;;
level 1 *)
succ 2;;
The aim of this exercise is to create a new text without comments. You are free to choose whatever lexical analysis tool you wish.

  1. Write a lexer able to recognize Objective CAML comments. These start with a (* and end with a *). Your lexer should ensure comments are balanced, that is to say the number of comment openings equals the number of comment closings. We are not interested in other constructions in the language which may contain characters (* and *).

  2. Write a program which takes a file, reads it, filters comments away and writes a new file with the remaining text.

  3. In Objective CAML character strings may contain any character, even the sequences (* and *). For example, character string "what(*ever te*)xt" should not be considered a comment. Modify your lexer to consider character strings.

  4. Use this new lexer to remove comments from an Objective CAML program .

Evaluator

We will use ocamlyacc to implement an expression evaluator. The idea is to perform the evaluation of expressions directly in the grammar rules.

We choose a (completely parenthesized) prefix arithmetic expression language with variable arity operators. For example, expression (ADD e1 e2 .. en) is equivalent to e1 + e2 + .. + en. Plus and times operators are right-associative and subtraction and division are left-associative.
  1. Define in file opn_parser.mly the parsing and evaluation rules for an expression.

  2. Define in file opn_lexer.mll the lexical analysis of expressions.

  3. Write a simple main program opn which reads a line from standard input containing an expression and prints the result of evaluating the expression.

Previous Contents Next