# Exercises on Section 4

## Exercise 9

For each of the following functions, give the signature and suggest a suitable precondition.

(a)

*TOUPPER*, which changes a string, containing only lower-case letters, into the corresponding string consisting of upper-case letters. (So, for example,*TOUPPER*(“word”) = “WORD”.)(b)

*REMOVELAST*, which, given a sequence, deletes its last member.(c)

*LAST*, which returns the last member of a sequence.

### Answer

### Solution

(a) This function inputs a string and outputs a string, therefore it has signature

*TOUPPER : SeqOfChar*→*SeqOfChar*. It requires a precondition that the input sequence consists entirely of lower-case letters.(b) The members of the sequence may come from any set, which we will denote by

*X*. The input is a sequence and the returned value is also a sequence. So the signature is*REMOVELAST : SeqOfX*→*SeqOfX*. The input sequence should contain at least one member (otherwise there is no last member to delete), so we need a precondition that the input sequence is not empty.(c) This is similar to (a), except that the returned value is an item from

*X*, rather than a sequence. The signature is*LAST : SeqOfX*→*X*. We again need the precondition that the input sequence is not empty.

## Exercise 10

Suppose that the days of the week are represented by numbers, with Mon-day represented by 1, Tuesday represented by 2, and so on, with Sunday represented by 7. Describe a function *TOMORROW2*, giving the next day with *Days* represented in this way.

### Answer

### Solution

You may have given this description.

**function** *TOMORROW2*(*d* **in** *Int*) **return in** *Int*

**pre** *d* is in the set {1,2,3,4,5,6,7}.

**post** The returned value is *t*, where:

if

*d*= 1 then*t*= 2if

*d*= 2 then*t*= 3if

*d*= 3 then*t*= 4if

*d*= 4 then*t*= 5if

*d*= 5 then*t*= 6if

*d*= 6 then*t*= 7if

*d*= 7 then*t*= 1.

Or you may have given a shorter description, such as:

**function** *TOMORROW2*(*d* **in** *Int*) **return in** *Int*

**pre** 1 ≤ *d* ≤ 7.

**post** The returned value is *t*, where:

*t* = *d* + 1 if 1 *= d =* 6;

*t* = 1 if *d* = 7.

Either of these answers is fine.

## Exercise 11

(a) With

*s*= “abcd”, evaluate each of:(i)

*AT*(1*, s*);(ii) PUT(2, s, AT(1, s)).

(b) For a general sequence

*s*, describe how the sequence*PUT*(2*, s, AT*(1*, s*)) is obtained from*s*.

The functions *AT* and *PUT* were described in Activity 16.

### Answer

### Solution

(a)(i) With

*s*= “abcd”,*AT*(1,*s*) = ‘a’.(ii) Then

*PUT*(2,*s*,*AT*(1,*s*)) =*PUT*(2,“abcd”,‘a’) = “aacd”.(b) In general,

*PUT*(2,*s*,*AT*(1,*s*)) is formed by replacing the second member of the sequence*s*with a copy of the first member of*s*.