Due: Mon, Oct 5
How to Submit
Submit a single file named
Read the Homework Policy! This describes what to do if you cannot solve a problem.
As in the last assignment, you’ll be defining the functions in the above template. This assignment builds on the definitions in Homework 1. You should start by doing the following:
Rename your solution to Homework 1 as
HW1.hs. You are also welcome to use my solution to Homework 1, which will be posted to Canvas.
Download HW2.template.hs and save it to the same directory as your
Rename the template to
HW2.hsand add your definitions directly to the file.
As before, the file contains
doctest comments that illustrate the intended behavior of each function on a few examples. You can use these examples as unit tests using
doctest. Feel free to add more examples to improve your test coverage.
Part 1: Reverse Polish Notation
In this part, you will be converting between the abstract syntax tree (AST) representation of arithmetic expressions (the
Expr data type) defined in your ‘HW1.hs’ file and a string encoding of that expression in Reverse Polish notation (RPN).
Observe that the
toRPN function is just another kind of pretty printer, similar to the one you wrote in Homework 1. This reveals that we can have multiple different concrete syntaxes (string encodings of a program) for one abstract syntax (tree encoding of a program containing only essential details).
fromRPN function works in the other direction: translating concrete syntax (
String) into abstract syntax (
Expr). This is called a parser.
Part 2: Syntactic Sugar
Often we can add new features to a language without extending its abstract syntax by translating the new features into existing features. Such new features are called “syntactic sugar”.
Doing this requires a bit of creativity if you haven’t seen it before. The trick is to think about how you can encode things like negation and subtraction using the operations you already have (literals, addition, and multiplication).
Questions to think about while you’re working on this part of the assignment.
What are the benefits of extending a language in this way?
What are the drawbacks?
Is there anything you can do with the add and multiply operations that are part of the abstract syntax that you can’t do with the negate and subtraction operations that you defined via syntactic sugar?
Is it always possible to add new features as syntactic sugar? If not, what is an example of a feature that cannot be added to this arithmetic expression language using syntactic sugar?
We’ll follow up on these questions in the next discussion assignment.