You are on page 1of 2

Prof. Dr.

Ralf Hinze TU Kaiserslautern


M.Sc. Sebastian Schloßer
Fachbereich Informatik
AG Programmiersprachen

Functional Programming: Exercise 6


Sheet published: Friday, June 10th
Exercise session: Thursday, June 23rd, 12:00

Exercise 6.1 (Skeleton: LazyNaturals.hs). The goal of this exercise is to develop a


datatype for lazy numeric computations. Normally, if a numeric expression is evaluated
at all, it must be evaluated completely. For example, the comparison length xs > 0 forces
evaluation of the entire list xs.
We introduce a new numeric datatype that supports natural numbers only. It represents
numbers using partitions i + j + . . . where the component values i, j, . . . are positive whole
numbers, i.e. i > 0, j > 0, . . . . We call these stuctures super-naturals:

infixr 6 :+
data Super natural = O | !natural :+ Super natural

A super-natural is either zero, represented by O, or of the form p :+ ps where p is


an evaluated part but ps may be unevaluated. The exclamation mark is a strictness
annotation, forcing the first argument of :+ to be fully evaluated. The second argument
still is evaluated lazily. The type parameter natural can be any numeric type, e.g. Integer .
Using super-naturals, the evaluation of length xs > O only needs the outermost con-
structor resulting from length xs to decide whether O > O = False or p :+ ps > O = True
applies (remember that p > 0 holds due to our invariant).

a) Implement a function

value :: Num natural ⇒ Super natural → natural

that reduces a super-natural to its natural value.


Example: value (1 :+ 3 :+ 5 :+ 1 :+ 4 :+ 2 :+ 1 :+ O) = 17
b) Implement functions

width :: Num natural ⇒ Super natural → natural


height :: (Num natural , Ord natural ) ⇒ Super natural → natural

computing the number of entries (width) and the largest entry (height) in the partition.
Example:

width (1 :+ 3 :+ 5 :+ 1 :+ 4 :+ 2 :+ 1 :+ O) = 7
height (1 :+ 3 :+ 5 :+ 1 :+ 4 :+ 2 :+ 1 :+ O) = 5

1
c) Implement addition and multiplication for super-naturals:

(+) :: Num natural ⇒ Super natural → Super natural → Super natural


(∗) :: Num natural ⇒ Super natural → Super natural → Super natural

Try to find a good balance between the width of the result and lazyness of the compu-
tation: The result should not be wider than the widest argument. Only when the kth
part of a result is demanded any kth part of an argument should be evaluated.
Make sure to maintain the invariant that the partitions contain positive numbers only.
d) Implement comparison for super-naturals:

compare :: (Num natural , Ord natural ) ⇒ Super natural → Super natural → Ordering

e) Why is the restriction to partitions of positive whole numbers important for your
implementation?

You might also like