function ASC(c in Char) return in Int
pre true.
post The returned value is the ASCII code of c, as given in Table 2.
function CHR(n in Int) return in Char
pre 32 ≤ n ≤ 126.
post The returned value is the character with ASCII code n, as given in Table 2.
Activity 18
Find each of:
- (a) ASC(‘j’);
- (b) CHR(43);
- (c) ASC(CHR(43));
- (d) CHR(ASC(‘j’)).
Discussion
- (a) Referring to Table 2, ASC(‘j’) = 106.
- (b) CHR(43) = ‘+’.
- (c) ASC(CHR(43)) means the result of applying the function ASC to CHR(43). So ASC(CHR(43)) = ASC(‘+’) = 43.
- (d) CHR(ASC(‘j’)) = CHR(106) = ‘j’.
ASC(CHR(n)) = n
CHR(ASC(c)) = c
Not every function can be paired up with an inverse function in this way. For example, the function FIRSTCHAR returns the first character in a string. Now different strings may have the same first character. (“This” and “The” both start with ‘T’, but are different strings.) With input ‘T’, a process attempting to reverse the effect of FIRSTCHAR would not know whether to return “This” or “The” (or “To”, or “Tom”, etc). The function FIRSTCHAR has no inverse function.
Activity 19
A simple cipher replaces each lower-case letter with the next one in alphabetical order. So ‘a’ is replaced by ‘b’, ‘b’ by ‘c’,. . . , ‘t’ by ‘u’, and so on. The letter z ‘ ’ is replaced by ‘a’. The function NEXT, specified below, corresponds to this coding.
function NEXT(c in Char) return in Char
pre c is a lower-case letter.
post If c lies between ‘a’ and ‘y’ then the returned value is the letter following c in alphabetical order. If c = ‘z’ then the returned value is ‘a’.
Does the function NEXT have an inverse function? If it does, describe this inverse function.
function NEXT(c in Char) return in Char
pre c is a lower-case letter.
post If c lies between ‘a’ and ‘y’ then the returned value is the letter following c in alphabetical order. If c = ‘z’ then the returned value is ‘a’.
Does the function NEXT have an inverse function? If it does, describe this inverse function.
Discussion
We can reverse the effect of NEXT by moving each character back one place in alphabetical order. This time, the special case is ‘a’, which must be moved to ‘z’. So NEXT does have an inverse function. If we call it BEFORE, it can be described as below.function BEFORE(c in Char) return in Char
pre c is a lower-case letter.
post If c lies between ‘b’ and ‘z ’ then the returned value is the letter preceding c in alphabetical order. If c = ‘a’ then the returned value is ‘z’.
No comments:
Post a Comment