2014 p01 q02 Solutions
2014 p01 q02 Solutions
lists, queues, (a) Write brief notes on the queue data structure and how it can be implemented
complexity efficiently in OCaml. In a precise sense, what is the cost of the main queue
operations? (It is not required to present OCaml code.) [6 marks]
Answer: A queue represents a sequence, allowing elements to be taken from the head and
added to the tail. Lists can implement queues, but append is a poor means of adding elements
to the tail. The solution is to represent a queue by a pair of lists, where
([x1 ; x2 , . . . , xm ], [y1 , y2 , . . . , yn ])
lists, exceptions, (b) Run-length encoding is a way of compressing a list in which certain elements
programming are repeated many times in a row. For example, a list of the form [a; a; a; b; a; a]
is encoded as [(3, a); (1, b); (2, a)]. Write a polymorphic function rl_encode to
perform this encoding. What is the type of rl_encode? [6 marks]
Answer:
let rec rl_encode = function
| [] -> []
| x::xs ->
let rec code n = function
| [] -> [(n, x)]
| y::ys ->
if x = y then
code (n + 1) ys
else
(n, x) :: rl_encode (y::ys)
in
code 1 xs
The type is ’a list -> (int * ’a) list. The code function can also be expressed with
guard clauses:
let rec code n = function
| [] -> [(n, x)]
| y::ys when x = y -> code (n + 1) ys
| ys -> (n, x) :: rl_encode ys
lists, (c) The simple task of testing whether two lists are equal can be generalised to allow
programming
1
— Solution notes —
Write a function genEquals n xs ys that returns true if the two lists xs and
ys are equal with no more than n errors, and otherwise false. You may assume
that n is a non-negative integer. [8 marks]
Answer:
let rec genEquals n xs ys =
match xs, ys with
| ([], []) -> true
| ([], y::ys) -> n > 0 && genEquals (n - 1) [] ys
| (x::xs, []) -> n > 0 && genEquals (n - 1) xs []
| ((x::xs), (y::ys)) ->
if x = y then genEquals n xs ys
else n > 0 && (genEquals (n - 1) xs ys
|| genEquals (n - 1) (x::xs) ys
|| genEquals (n - 1) xs (y::ys))
All OCaml code must be explained clearly and should be free of needless complexity.