Professional Documents
Culture Documents
Ex2 Solutions
Ex2 Solutions
data Tree elem = Empty | Node (Tree elem) elem (Tree elem)
a) Write a function left :: Tree a → Maybe a that returns the left-most element in the
given tree, or Nothing if the tree is empty.
b) Write a function reverseTree :: Tree a → Tree a that returns a tree whose inorder
traversal is the reverse of the original trees’s inorder traversal.
The specification is: inorder (reverseTree t) == reverse (inorder t).
Hint: Solve it in a graphical way first, then write the code.
Exercise 2.2 (Skeleton: Calculus.hs). Lisa Lista’s younger brother just went through
differential calculus at high school. She decides to implement derivatives in Haskell to
be able to easily double-check his homework solutions. To this end she introduces the
following datatype:
infixl 6 :+:
infixl 7 :∗:
infixl 8 :ˆ:
infixl 9 :◦:
data Function
= Const Rational — constant function
| Id — identity
| Function :+: Function — addition of functions
| Function :∗: Function — multiplication of functions
| Function :ˆ: Integer — power with constant exponent
| Function :◦: Function — composition of functions
deriving (Show )
1
The idea is that each element of Function represents a function over the rationals1 e.g.
Id represents \x → x , Const r represents \x → r , Id :ˆ: (−2) represents \x → x ˆˆ(−2),
and (Id :ˆ: 5) :◦: (Id :+: Const 3) represents \x → (x + 3)ˆˆ5 (which could also be written
as (\x → x ˆˆ5) ◦ (\x → x + 3)). Note that we use (ˆˆ) instead of (ˆ) because the former
allows for negative exponents, where x ˆˆ(−n) == 1 / (x ˆˆn).
In general, if e1 represents f1 and e2 represents f2 , then e1 :+: e2 represents the
function \x → (f1 x ) + (f2 x ), e1 :∗: e2 represents the function \x → (f1 x ) ∗ (f2 x ),
e1 :◦: e2 represents the function \x → f1 (f2 x ), and e1 :ˆ: n represents the function
\x → (f1 x )ˆˆn.
a) Define a function apply :: Function → (Rational → Rational ) that applies the repre-
sentation of a function to a given value. In a sense, apply maps syntax to semantics:
the representation of a function is mapped to the actual Haskell function.
c) After Lisa has captured the rules of derivatives as a Haskell function, she tests the
implementation on a few simple examples. The initial results are not too encouraging:
2
simplify :: Function → Function
simplify (Const c) = Const c
simplify (Id ) = Id
simplify (f :+: g) = plus (simplify f ) (simplify g)
where plus (Const 0) g =g
plus f (Const 0) = f
plus (Const x ) (Const y) = Const (x + y)
plus f g = f :+: g
simplify (f :∗: g) = mult (simplify f ) (simplify g)
where mult (Const 0) g = (Const 0)
mult f (Const 0) = (Const 0)
mult (Const 1) g =g
mult f (Const 1) = f
mult (Const x ) (Const y) = Const (x ∗ y)
mult f g = f :∗: g
simplify (f :ˆ: n) = power (simplify f ) n
where power 0 = Const 1
power f 1 =f
power f n = (f :ˆ: n)
simplify (f :◦: g) = compose (simplify f ) (simplify g)
where compose Id g =g
compose f Id =f
compose f g = (f :◦: g)