Pages

20.8.11

4.2 Functions defined through cases

In each of the examples considered so far, the function has had its semantics expressed using a formula or a general rule. Some functions have their semantics expressed simply by listing the output for each possible input. For example, let Days be the set of days of the week, and the function TOMORROW have signature DaysDays, and return the day following the input day. If we represent Days using the strings {“Mon”, “Tues”, “Wed”, “Thurs”, “Fri”, “Sat”, “Sun”}, then we can describe the corresponding representation of the function TOMORROW as below.
function TOMORROW1(d in SeqOfChar) return in SeqOfChar
pre d is in the set {“Mon”,“Tues”,“Wed”,“Thurs”,“Fri”,“Sat”,“Sun”}.
post The returned value is t, where:
  • if d = “Mon” then t = “Tues”

  • if d = “Tues” then t = “Wed”

  • if d = “Wed” then t = “Thurs”

  • if d = “Thurs” then t = “Fri”

  • if d = “Fri” then t = “Sat”

  • if d = “Sat” then t = “Sun”

  • if d = “Sun” then t = “Mon”.

We distinguish the abstraction (the function TOMORROW) from its representation (the function TOMORROW1), because different representations of the set Days will lead to different representations of the function TOMORROW (see, for example, Exercise 2).

Activity 17

Suppose that a particular breakfast cereal is sold in sizes Small, Medium and Large, and that we choose to represent these by the characters ‘S’, ‘M’ and ‘L’. Their respective prices, in pence, are 89 for ‘S’, 119 for ‘M’ and 159 for ‘L’. Describe a function CEREALPRICE that takes a size as input and returns the associated price.

Discussion

We can describe this function as follows.
function CEREALPRICE(c in Char) return in Int
pre c is in the set {‘S’, ‘M’, ‘L’}.
post The returned value is p, where:
  • if c = ‘S’ then p = 89

  • if c = ‘M’ then p = 119

  • if c = ‘L’ then p = 159.

No comments:

Post a Comment