(iv) IF
<test>
THEN <instruction-1>
ELSE <instruction-2>
isdef an instruction
NOTE: Both <instruction-1> and <instruction-2>
are instructions, either as previously defined
in clauses (i)-(iii), or as defined here.
b) Semantics of this clause:
if <test> is true, then
Karel does <instruction-1>;
if <test> is false,
then Karel does <instruction-2>;
in either case,
Karel then goes on to next instruction
Again, I won't show the flowchart,
but see
Lecture
Notes #4 for a sample.
e.g.) Problem:
Karel is to follow a diagonal path from (1,1)
up to the right, harvesting a beeper at each
corner if there is one, & planting one if there
isn't & if he has one in his bag.
Strategy:
1. K should go to the diagonally
opposite corner;
2. if there's a beeper on that corner,
3. then he should harvest it
4. else he should plant one
(etc.: repeat this as often as you want)
Refinements:
1.1. use
"go-to-diagonally-opposite-corner"
as defined in the last
example
2.1. if next-to-a-beeper
3.1. then pickbeeper
4.1. else plant-beeper
Next refinement step:
4.1.1. define-new-instruction
plant-beeper as
if any-beepers-in-beeper-bag
then putbeeper
EXERCISE FOR THE READER: TRY IMPLEMENTING
THIS FULL PROGRAM, CREATE SEVERAL INTERESTING
INITIAL WORLDS, AND RUN THE PROGRAM ON THEM.
c) In "if next-to-a-beeper
then pickbeeper
else plant-beeper"
do we have to check that there's NO beeper?
* NO: the "else" test is automatic
d) This could be written using "nested" if-then
(instead of defining the
new instruction
"plan-beeper"):
if next-to-a-beeper,
then pickbeeper
else if any-beepers-in-beeper-bag
then putbeeper
e) BUT nested "if-then"s can lead to ambiguity,
& should be avoided
if possible:
e.g., suppose we reverse the test:
if
not-next-to-a-beeper
then if any-beepers-in-beeper-bag
then putbeeper
else pickbeeper.
It looks as if this
is an "if-then-else" instruction,
but it is really simply
an "if-then" instruction.
The "else" clause does not
belong to the
"not-next-to-a-beeper" test.
Rather, it belongs to the
"any-beepers-in-
beeper-bag" test.
Try running this to see how it actually behaves.
This is called the "dangling-else"
problem.
For more information on
this, as well as some
other interesting aspects
of if-then-else
instructions, see Lecture
Notes #9A.
we can present another clause
of our
recursive definition of
instruction:
(v) ITERATE
<n> TIMES
<instruction>
isdef an instruction
QUESTION:
Could n be 0? Try writing an
"iterate 0 times" program to see what happens!
e.g.) To have Karel pick beepers on the diagonal
if any are present, and to do this 8 times
(as in an
earlier example), we could write
iterate 8 times
get-beeper
instead of writing "get-beeper" 8 times.
QUESTION:
How can we have Karel execute some instruction
n ² times
(where n ² = n * n;
e.g., 3 ² = 3*3 = 9)?
ANSWER: See Lecture
Notes #10 :-)