## Exercises for Week 5: Recursive Datatypes

Here are some exercises designed to help you practice programming with recursive datatypes.

If you do not have time to do all these exercises, don't worry.
The exercises are intended to provide enough work to keep the *most*
experienced students busy. If you do all exercises marked with an (*) you have
probably understood this week's material.

Good luck!

### 0 (*). Expression and Integer Trees

#### Expressions

From Thompson's book, read Chapter 14, sections 14.2 to 14.4. Alternatively, you can take a look at the datatype**Expr**for expressions with variables from the lecture: SymbolicExpressions.hs.

Among other things, the book introduces a datatype `Expr`

which is similar to the type used in the lecture. Given an expression we want to evaluate it. This is done usingdataExpr=LitInt|AddExprExpr|SubExprExpr

`eval`

defined by
We also want be able to show an expressioneval::Expr->Inteval(Litn)=neval(Adde1e2)=evale1+evale2eval(Sube1e2)=evale1-evale2

showExpr::Expr->StringshowExpr(Litn)=shownshowExpr(Adde1e2)="("++showExpre1++"+"++showExpre2++")"showExpr(Sube1e2)="("++showExpre1++"-"++showExpre2++")"

**A.** Give calculations of

eval(Lit67)eval(Add(Sub(Lit3) (Lit1)) (Lit3))showExpr(Add(Lit67) (Lit(-34)))

**B(*).** Define the function

which counts the number of operators in an expression.size::Expr->Int

**C(*).** Add the operations of multiplication and integer
division to the type `Expr`

, and redefine the
functions `eval`

, `showExpr`

, and `size`

to
include the new cases. What does your `eval`

do when you
divide by zero? Write one version of `eval`

with the result
type `Maybe Int`

.

**D.** Instead of adding extra constructors to the `Expr`

datatype as in **C** it is possible to factor the definitions

Show how the functionsdataExpr=LitInt|OpOpsExprExprdataOps=Add|Sub|Mul|Div

`eval`

, `showExpr`

,
and `size`

are defined for this type. How would you add yet
another extra operation **Mod**

for remainder on integer
division?
**E.**
In Haskell back-quotes allow us to use constructors in infix form
(indeed any function) like in `(`

.
However, if this expression is shown
(using **Lit** 3) `**Add**` (**Lit** 15)

)
it appears in prefix
form as **deriving** **Show**

.
**Add** (**Lit** 3) (**Lit** 15)

It is also possible to use infix operators for constructor names where
the first character must be a `':'`

. We can, e.g.,
redefine `Expr`

as

data Expr = Lit Int | Expr :+: Expr | Expr :-: ExprRedefine the above functions using this datatype with infix constructors.

#### Integer Trees

A*tree of integers*is either nil or given by combining a value and two sub-trees. In Haskell we can introduce the datatype of integer trees

`NTree`

by
We can sum the nodes and calculate the depths of a tree as followsdataNTree=NilT|NodeIntNTreeNTree

sumTree::NTree->IntsumTreeNilT=0sumTree(Nodent1t2)=n+sumTreet1+sumTreet2depth::NTree->IntdepthNilT=0depth(Nodent1t2)=1+max(deptht1) (deptht2)

**A.** Give a calculation of

sumTree(Node3 (Node4NilTNilT)NilT)depth(Node3 (Node4NilTNilT)NilT)

**B(*).** Define functions to return the left- and right-hand
sub-trees of an `NTree`

.

**C(*).** Define a function to decide whether a number is an
element of an `NTree`

.

**D.** Define functions to find the maximum and minimum values
held in an `NTree`

.

**E(*).** A tree is reflected by swapping left and right
sub-trees, recursively. Define a function to reflect
an `NTree`

. What is the result of reflecting twice? Write a
QuickCheck property for that!

(In order to be able to test your properties, you have to
make **NTree** an instance of Arbitrary.)

**F.** Define functions

which turn a tree into a list. The functioncollapse,sort::NTree->[Int]

`collapse`

should
enumerate the left sub-tree, then the value at the node and finally
the right sub-tree; `sort`

should sort the elements in
ascending order. For example,
Write a suitable QuickCheck property for your functions!collapse(Node3 (Node4NilTNilT)NilT)=[4,3]sort(Node3 (Node4NilTNilT)NilT)=[3,4]

### 1 (*). File Systems

A*file*either contains data or is a directory. A

*directory*contains other files (which may themselves be directories) along with a name for each one.

**A.**Design a data type to represent the contents of a directory. Ignore the contents of files: you are just trying to represent file names and the way they are organised into directories here.

**B.**Define a function to search for a given file name in a directory. You should return a path leading to a file with the given name. Thus if your directory contains a, b, and c, and b is a directory containing x and y, then searching for x should produce b/x.

### 2. Exercises on Propositional Logic

A*proposition*is a boolean formula of one of the following forms:

- a variable name (a string)
- p & q
*(and)* - p | q
*(or)* - ~p
*(not)*

where p and q are propositions. For example, **p | ~p** is a proposition.

**B.** Define a function

vars::Prop->[String]

which returns a list of the variables in a proposition. Make sure each variable appears only once in the list you return.

Suppose you are given a list of variable names and their
values, of type Bool, for example,
`[("p",True),("q",False)]`

.
Define a function

which determines whether the proposition is true when the variables have the values given.truthValue::Prop->[(String,Bool)]->Bool

**C.** Define a function

tautology::Prop->Bool

which returns `True`

if the proposition holds for all values of
the variables appearing in it.

Congratulations! You have implemented a simple theorem prover.

### 3 (*). Exercises on type Expr from the Lecture

Take a look at the datatype `Expr`

for expressions with variables
from the lecture:
SymbolicExpressions.hs.

In the lecture, we saw a function for differentiating expressions, called
`diff`

(Swedish: "derivera").

diff::Expr->Name->Exprdiff(Numn)x=Num0diff(Addab)x=Add(diffax) (diffbx)diff(Mulab)x=Add(Mula(diffbx)) (Mulb(diffax))diff(Vary)x|x==y=Num1|otherwise=Num0

**A.**
Define a property that checks that, for each expression e, the derivative of e
to x does not contain more variables than e.

Does the opposite hold also?

The result of the `diff`

function often contains expressions that
can be simplified considerably.

**B.**(*) Define a function **simplify** that, given an expression e,
creates an expression that is equivalent to e, but simplified. Examples of
simplifications you could do are:

- 2+3 --> 5
- 2*x+6+5*x+6 --> 7*x+12
- 0*x+-2+5*y+3 --> 5*y+1

**Hint:** This exercise is more open-ended.

You can try to define **simplify** recursively. You will however
notice that it is difficult to accomplish many simplifications. Take a look at
the function **assoc** in chapter 14 in Thompson's book:

assoc::Expr->Exprassoc(Add(Adde1e2)e3)=assoc(Adde1(Adde2e3))assoc(Adde1e2)=Add(assoce1) (assoce2)assoc(Sube1e2)=Sub(assoce1) (assoce2)assoc(Litn)=Litn

(A different, but more ambitious, approach is to design a new type, that
represents a *normal form* for expressions, for example
polynomials. Your `simplify`

function could simply transform an
expression into a polynomial, and back into expressions again. How would you
model polynomials over multiple variables as a type in Haskell?)

Make sure that the following property holds for your `simplify`

function:
for each expression e, evaluating it in an environment generates the
same result before and after simplifying:

prop_SimplifyCorrect::Expr->Env->Propertyprop_SimplifyCorrecte(Envenv)=evalenve===evalenv(simplifye)

**C.** Define a property:

that checks that the result of simplification does not "leave any junk". In other words, the result of simplification should for example not have subexpressions of the form:prop_SimplifyNoJunk::Expr->Bool

**Add**(**Num**`n`) (**Num**`m`)**Mul**(**Num**0)`b`**Add**`a``a`

This property boils down to defining a function
`noJunk:: Expr -> Bool`

.

**D.** Define a property:

that checks that differentiating an expression and then simplifying it should have the same result as simplifying it first, then deriving, and then simplifying.prop_SimplifyDiff::Expr->Bool

Do you expect it to hold? Does it actually hold for your simplification function?