a) test reversal:
IF <test>
THEN <instr-1>
ELSE <instr-2>
is equivalent to
IF <opposite test>
THEN <instr-2>
ELSE <instr-1>
e.g., IF next-to-a-beeper
THEN pickbeeper
ELSE move
is equiv to
IF not-next-to-a-beeper
THEN move
ELSE pickbeeper
e.g., the awkard program:
IF
next-to-a-beeper
THEN <do next instr>
ELSE move
is equiv to
IF
not-next-to-a-beeper
THEN move
(don't need ELSE !)
b) bottom factoring:
IF facing-north
THEN
BEGIN
move;
turnleft
END
ELSE
BEGIN
putbeeper;
turnleft
END
which has a common instruction (turnleft) that can
be "factored out"
- cf. (2*3) + (4*3), which
= 6+12 = 18
= (2+4)*3, which = 6*3 = 18
& is equiv to:
IF facing-north
THEN move
ELSE putbeeper;
turnleft
c) top factoring:
IF <test>
THEN
BEGIN
<instr-1>;
<instr-2>
END
ELSE
BEGIN
<instr-1>;
<instr-3>
END
is equiv to
<instr-1>;
IF <test>
THEN <instr-2>
ELSE <instr-3>
d) redundant-test factoring:
IF <test-1>
THEN
BEGIN
<instr-1>;
IF <test-1>
THEN <instr-2>
END
is equiv to
IF <test-1>
THEN
BEGIN
<instr-1>;
<instr-2>
END
Warning: Only works if <instr-1> doesn't change
the condition of <test>
B. Dangling Else
IF facing-north
THEN IF front-is-clear
THEN move
ELSE turnleft
vs.
IF facing-north
THEN IF front-is-clear
THEN move
ELSE turnleft
There are 2 different intents here, but only 1 instr.
Therefore, to get the intent of the 2nd, do:
IF facing-north
THEN
BEGIN
IF front-is-clear
THEN move
END
ELSE turnleft