Revise the definition of the count-from procedure presented
in
the reading on
recursion with natural numbers so that it enforces the precondition
that its first argument be less than or equal to its second argument.
Revise the definition of the odd-factorial procedure in
exercise 6 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?
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.
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 null) ()
This document is available on the World Wide Web as
http://www.cs.grinnell.edu/~gum/courses/151/labs/preconditions-and-postconditions.xhtml
created February 4, 2000
last revised August 9, 2001
John David Stone (stone@cs.grinnell.edu) and Ben Gum (gum@cs.grinnell.edu)