15.08.2013 Views

General Computer Science; Problems and Solutions for ... - Kwarc

General Computer Science; Problems and Solutions for ... - Kwarc

General Computer Science; Problems and Solutions for ... - Kwarc

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Problem 1.12 (Compressing binary lists)<br />

Define a data type of binary digits. Write a function that takes a list of binary digits <strong>and</strong> returns<br />

an int list that is a compressed version of it <strong>and</strong> the first binary digit of the list (needed <strong>for</strong><br />

reconversion). For example,<br />

ZIPit([zero,zero,zero, one,one,one,one,<br />

zero,zero,zero, one, zero,zero]) -> (0,[3,4,3,1,2]),<br />

because the binary list begins with 3 zeros, followed by 4 ones etc.<br />

Solution:<br />

datatype bin = zero | one;<br />

local fun ZIP(nil,_,cnt) = [cnt] |<br />

ZIP(hd::tl, last, cnt) =<br />

if hd=last then ZIP(tl, hd, cnt+1)<br />

else cnt::ZIP(tl, hd, 1);<br />

in<br />

fun ZIPit(hd::tl) = (hd, ZIP(tl, hd, 1))<br />

end;<br />

13

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!