Preconditions and postconditions

Course links

Exercise 1

Use the Languages menu to switch to the PLT Textual dialect of Scheme (so that the error procedure is available). Revise the definition of the count-from procedure presented in the reading on recursion with integers so that it enforces the precondition that its first argument be less than or equal to its second argument.

Exercise 2

Revise the definition of the odd-factorial procedure in exercise 5 of the lab on recursion with natural numbers as a husk-and-kernel program in which the husk enforces the precondition.

How can we be certain, in this case, that none of the calls we make to the kernel procedure violates the precondition?

Exercise 3

Define and test a procedure named index that takes a symbol sym and a list ls of symbols as its arguments and returns the number of list elements that precede the first occurrence of sym in ls:

> (index 'gamma (list 'alpha 'beta 'gamma 'delta))
2
> (index 'easy (list 'easy 'medium 'difficult 'impossible))
0
> (index 'the (list 'and 'the 'cat 'sat 'on 'the 'mat))
1

Arrange for index to signal an error (by invoking the error procedure) if sym does not occur at all as an element of ls.

Exercise 4

Define and test a procedure named substitute that takes three arguments -- a symbol new, another symbol old, and a list ls of symbols -- and returns a list just like ls except that every occurrence of old has been replaced with an occurrence of new. Use the husk-and-kernel structure to make sure that new and old are symbols and that ls is a list of symbols before starting into the recursion.

> (substitute 'alpha 'omega (list 'phi 'chi 'psi 'omega 'omega)
(phi chi psi alpha alpha)
> (substitute 'starboard 'port (list 'port 'starboard 'port 'port))
(starboard starboard starboard starboard)
> (substitution 'in 'out '())
()

Exercise 5

For students who know about complex numbers: State the preconditions of the expt procedure that is built into Scheme.

I am indebted to Professor Ben Gum for his contributions to the development of this lab.