g- substr(S, length(S) , 1)
h- substr(S, length(S-1), 2)
Answers:
g- If S = 'Algorithm', then this returns 'm'
h- If S = 'Algorithm', then this returns 'hm'
In general:
g- This returns the last character of S
h- This returns the last 2 characters of S
Question:
Can you write a "substr" function that returns the
last 3 characters of S? ... the last 4?
Save, compile, and run these
on the following
inputs:
'mouse'
'buffalo'
'memory'
'dog'
Both programs have the same I/O behavior.
b) But, if you look at the programs carefully,
I think you will see that
the main body of
"plurals2.p" is easier to
read and to understand
than the main body of "plurals.p"
c) "plurals" uses: substr(noun, length(noun),
1)
"plurals2" uses: LastLetter(noun)
* which
is what that "substr" function computes
"plurals" uses:
substr(noun, 1, length(noun)-1)
"plurals2" uses:
AllButLastLetter(noun)
* which
is what that "substr" function computes
d) Digression:
There is an implementation-dependent
detail
that we have to take care
of:
In Unix Pascal, we can't
use "varying [n] of char"
inside Pascal's version
of Karel's "define-new-
instruction".
Solution:
Use a "type" declaration
together with a slightly
different "var" declaration:
type string = varying [20]
of char;
var noun : string;
"type" declarations go before "var" declarations.
e) A Pascal function -- which is one of Pascal's
versions of Karel's "define-new-instruction"
--
has:
a name
an input
an output
an algorithm (i.e., a procedure
that converts
the input into the output)
e.g.) function LastLetter(word : string) : string;
begin
LastLetter := substr(word, length(word), 1)
end;
"function" is a reserved word;
The name of this Pascal function is "LastLetter"
The input of this Pascal function is called "word"
The type of the input is "string"
The type of the output is "string"
The algorithm is to compute the "substr" function
as shown, and assign the result to the name of
the function.
More examples will be shown next time.