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.
0 (*). Expression and Integer Trees
ExpressionsFrom 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: ExprVar.hs.
Among other things, the book introduces a datatype
which is similar to the type I used in the lecture. Given an expression we want to evaluate it. This is done usingdata Expr = Lit Int | Add Expr Expr | Sub Expr Expr
We also want be able to show an expressioneval :: Expr -> Int eval (Lit n) = n eval (Add e1 e2) = eval e1 + eval e2 eval (Sub e1 e2) = eval e1 - eval e2
showExpr :: Expr -> String showExpr (Lit n) = show n showExpr (Add e1 e2) = "(" ++ showExpr e1 ++ "+" ++ showExpr e2 ++")" showExpr (Sub e1 e2) = "(" ++ showExpr e1 ++ "-" ++ showExpr e2 ++")"
A. Give calculations of
eval (Lit 67) eval (Add (Sub (Lit 3) (Lit 1)) (Lit 3)) showExpr (Add (Lit 67) (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
include the new cases. What does your
eval do when you
divide by zero? Write one version of
eval with the result
D. Instead of adding extra constructors to the
datatype as in C it is possible to factor the definitions
Show how the functionsdata Expr = Lit Int | Op Ops Expr Expr data Ops = Add | Sub | Mul | Div
sizeare defined for this type. How would you add yet another extra operation
Modfor remainder on integer division?
In Haskell back-quotes allow us to use constructors in infix form
(indeed any function) like in
(Lit 3) `Add` (Lit 15).
However, if this expression is shown
it appears in prefix
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.,
data Expr = Lit Int | Expr :+: Expr | Expr :-: ExprRedefine the above functions using this datatype with infix constructors.
Integer TreesA 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
We can sum the nodes and calculate the depths of a tree as followsdata NTree = NilT | Node Int NTree NTree
sumTree :: NTree -> Int sumTree NilT = 0 sumTree (Node n t1 t2) = n + sumTree t1 + sumTree t2 depth :: NTree -> Int depth NilT = 0 depth (Node n t1 t2) = 1 + max (depth t1) (depth t2)
A. Give a calculation of
sumTree (Node 3 (Node 4 NilT NilT) NilT) depth (Node 3 (Node 4 NilT NilT) NilT)
B(*). Define functions to return the left- and right-hand
sub-trees of an
C(*). Define a function to decide whether a number is an
element of an
D. Define functions to find the maximum and minimum values
held in an
E(*). A tree is reflected by swapping left and right
sub-trees, recursively. Define a function to reflect
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]
collapseshould enumerate the left sub-tree, then the value at the node and finally the right sub-tree;
sortshould sort the elements in ascending order. For example,
Write a suitable QuickCheck property for your functions!collapse (Node 3 (Node 4 NilT NilT) NilT) = [4,3] sort (Node 3 (Node 4 NilT NilT) NilT) = [3,4]
1 (*). File SystemsA 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.
2. Exercises on Propositional LogicA 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.
Propto represent propositions.
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,
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
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: ExprVar.hs.
In the lecture, I showed a function for differentiating expressions, called
diff (Swedish: "derivera").
diff :: Expr -> Name -> Expr diff (Num n) x = Num 0 diff (Add a b) x = Add (diff a x) (diff b x) diff (Mul a b) x = Add (Mul a (diff b x)) (Mul b (diff a x)) diff (Var y) x | x == y = Num 1 | otherwise = Num 0
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
We have made a small start for you in the file ExprVar.hs
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 -> Expr assoc (Add (Add e1 e2) e3) = assoc (Add e1 (Add e2 e3)) assoc (Add e1 e2) = Add (assoc e1) (assoc e2) assoc (Sub e1 e2) = Sub (assoc e1) (assoc e2) assoc (Lit n) = Lit n
(A different, but more ambitious, approach is to design a new type, that
represents a normal form for expressions, for example
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
for each expression e, evaluating it in an environment generates the
same result before and after simplifying:
prop_SimplifyCorrect :: Expr -> Env -> Property prop_SimplifyCorrect e (Env env) = eval env e === eval env (simplify e)
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.
We have already made a small start for you in
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?