Directory UMM :wiley:Public:college:compsci:bergin:

(1)

7

2

PRIMITIVE INSTRUCTIONS

AND SIMPLE PROGRAMS

2.1

CHANGING POSITION

o o o o o

o o o o o o

o o o o o o o

o o o o o o o

o o o o o

o o o o o o

o o o o o

o o o o o o

o o o

o o o o o o o o o

o o o o o

o o o o

o o o o o o o o

o o o o o o

o o o o o o

o o o o o o o

o o o o o o o

o o o o o o

o o o o o o

o o

o

o o o o o o o

o o o o o o o o o

o o o o

o o o o o o o

o o o o o

This chapter begins ur study f the r b t pr gramming language. We will start with a detailed explanati n f the primitive instructi ns that are built int every r b t’s v cabulary. Using these instructi ns, we can instruct any r b t t m ve thr ugh the w rld and handle beepers. Secti n 2.6 sh ws a c mplete r b t pr gram and discusses the elementary punctuati n and grammar rules f the r b t pr gramming language. By the end f this chapter we will be able t write pr grams that instruct r b ts t perf rm simple bstacle av idance and beeper transp rtati n tasks.

Bef re explaining the primitive instructi ns f the r b t pr gramming language, we must first define the technical term A r b t executes an instructi n by per-f rming the instructi n’s ass ciated acti n r acti ns. The r b t executes a pr gram by executing a sequence f instructi ns that are given t it by the helic pter pil t. Each instructi n in such a sequence is delivered t the r b t in a message, which directs

ne r b t t perf rm ne instructi n in the pr gram.

Every r b t understands tw primitive instructi ns that change its p siti n. The first f these instructi ns is , which changes a r b t’s l cati n.

When a r b t executes a instructi n, it m ves f rward ne bl ck; it c ntinues t face the same directi n. T av id damage, a r b t will n t m ve f rward if it sees a wall secti n r b undary wall between its current l cati n and the c rner t which it w uld m ve. Instead, it turns itself ff. This acti n, called an will be explained further in Secti n 2.7.

Fr m this definiti n we see that a r b t executes a instructi n by m ving f r-ward t the next c rner. H wever, the r b t perf rms an err r shut ff when its fr nt is bl cked. B th situati ns are illustrated in Figure 2-1. Figure 2-1 sh ws the successful executi n f a instructi n. The wall secti n is m re than ne half-bl ck away and cann t bl ck this r b t’s m ve.

execute:

error shutoff,

move

move move

move


(2)

Robot has executed an error shutoff

Figure 2-1 A Figure 2-1 B

Figure 2-2

2.2

TURNING IN PLACE

o o o o o o o

o o o o o

o o o o

o o o o o o

o o o o o o

o o

o o o o o

o o o o

o o o

o o o o o o

o o

o o o o o o o o

o o o o o o o o o

In c ntrast, Figure 2-2 sh ws an inc rrect attempt t m ve. When this r b t tries t execute a instructi n in this situati n, it sees a wall secti n. Relying n its self-preservati n instinct, it perf rms an err r shut ff.

The sec nd primitive instructi n that changes a r b t’s p siti n is . This instructi n changes the directi n in which the r b t is facing but d es n t alter its l cati n.

A r b t executes a instructi n by piv ting 90 t the left. The r b t remains n the same street c rner while exe-cuting a instructi n. Because it is imp ssible f r a wall secti n t bl ck a r b t’s turn, cann t cause an err r shut ff.

A r b t always starts a task n s me c rner, facing either n rth, s uth, east, r west. A r b t cann t travel fracti ns f a bl ck r turn at ther than 90 angles. Alth ugh

move move

move move

turnLeft

turnLeft turnLeft

turnLeft

turnLeft

8

8

o o o o

o o o o o

o o o

o o o o

o

A R b t in the Initial A R b t in the Final Sit-Situati n Bef re a Instructi n uati n After Executing a Instructi n

The Result f a R b t Attempting t When Its Fr nt Is Bl cked In an Err r Shut ff


(3)

2.3

FINISHING A TASK

2.4

HANDLING BEEPERS

o o o o o

o o o o o o o o o o

o

o o o

o o o o o o o o

o o o o o o o

o o o o

o o o o o o o o

o o o o o o

o

o o o o

o o o o

o o o o

o o o o o

o

o o o o o o

o o o o o

o o o

o o o

o

o o o o o

o o o o o o

o o o o o o

o o o

o o

o o o o

o o o o

o o o o o o

o o o

o o

o o o o o o o

o o o o o o o o

o o o o o o o o

and change the r b t’s p siti n, after executing either f these instructi ns, the r b t still is n s me c rner and still is facing ne f the f ur c mpass directi ns.

Karel-Werke’s designer purp sely did n t pr vide a built-in instruc-ti n. W uld adding a t the primitive instructi ns all w the r b t t perf rm any task it cann t acc mplish with ut ne? A m ment’s th ught—and the right flash f insight—sh ws that the instructi n is unnecessary; it d es n t permit r b ts t acc mplish any new tasks. The key bservati n f r verifying this c nclusi n is that a r b t can manage the equivalent f a instructi n by executing three instructi ns.

We need a way t tell a r b t that its task is finished. The instructi n fulfills this requirement.

When a r b t executes a instructi n, it turns ff and is incapable f executing any m re instructi ns until restarted n an ther task. The last instructi n executed by every r b t in a pr -gram must be a instructi n.

Every r b t understands tw instructi ns that permit it t handle beepers. These tw instructi ns perf rm pp site acti ns.

When a r b t executes a instructi n, it picks up a beeper fr m the c rner n which it is standing and then dep sits the beeper in its beeper-bag. If a in-structi n is attempted n a beeperless c rner, the r b t per-f rms an err r shut per-fper-f. On a c rner with m re than ne beeper the r b t picks up ne, and nly ne, f the beepers and then places it in the beeper-bag.

A r b t executes a instructi n by extracting a beeper fr m its beeper-bag and placing the beeper n the cur-rent street c rner. If a r b t tries t execute a

instructi n with an empty beeper-bag, the r b t perf rms an err r shut ff. If the r b t has m re than ne beeper in its beeper-bag, it extracts ne, and nly ne, beeper and places it

n the current c rner.

Beepers are s small that r b ts can m ve right by them; nly wall secti ns and b und-ary walls can bl ck a r b t’s m vement. R b ts are als very adept at av iding each

ther if tw r m re sh w up n the same c rner simultane usly.

move turnLeft

turnRight turnRight

turnRight

turnRight turnLeft

turnOff

turnOff turnOff

turnOff

pickBeeper pickBeeper

pickBeeper

putBeeper putBeeper


(4)

2.5

ROBOT DESCRIPTIONS

o o o

o o o o o

o o o o o

o o o o o o o

o o o o o o o o o o

o o o o o o

o o o o o

o o

o o o o o o o o o

o o

o o o o o

o o o

o o o o o o

o o o oo o

o o o o

o o o o

o o o o o

o o o o o o o

o o

o o o

o o o o o

o o o o o o o

o o o o o

All r b ts pr duced by Karel-Werke have at least the capabilities just described. As we will see, such r b ts are very primitive, and we might like r b ts with additi nal abilities. Theref re, we must have s me way t describe th se extra abilities s that the fact ry can build a r b t t ur specificati ns. Karel-Werke empl ys a simple r b t pr gramming language t describe b th r b t abilities and the lists f r b t in-structi ns, called The simple m del f r b t described ab ve is called the class. The specificati n f the class in the r b t pr gram-ming language f ll ws.

F ll wing the m del class name is a list f instructi ns f r this kind f r b t. The list is always written in braces and , and the final brace is always f ll wed by a semic l n. Each entry is als terminated by a semic l n.

The five instructi ns, thr ugh , name acti ns that

can perf rm. We defined each f these acti ns in the f reg ing secti ns, and we will see many examples f their use thr ugh ut this b k. The w rd prefixes each f these instructi ns t indicate that they return n feedback when executed. Later we will see additi nal instructi ns that d pr duce feedback when executed, rather than changing the state f the r b t as these instructi ns all d . The matching parentheses that f ll w the instructi n names mark them as the names f acti ns that a r b t will be able t carry ut.

A sample task f r an might be t start at the rigin, facing east, and then walk three bl cks east t a c rner kn wn t have a beeper, pick up the beeper, and n that c rner. A c mplete pr gram t acc mplish this task is sh wn next. In this pr gram we name the r b t , but we c uld use any c nvenient name.

1

programs.

1

ur_Robot ur_Robot

class ur_Robot {

void move(); void turnOff(); void turnLeft(); void pickBeeper(); void putBeeper(); };

{ }

move putBeeper ur_Robots

void

ur_Robot turnOff

Karel

task {

ur_Robot Karel(1, 1, East, 0);

// Deliver the robot to the origin (1,1), // facing East, with no beepers.

Karel.move();

ur o o o o o ur o o

o oo oo

is a German prefix meaning “ riginal” r “primitive.” The pr nunciati n f is similar t the s und f “ r” in “p r.”


(5)

Initial Situation Final Situation

Figure 2-3

2.6

A COMPLETE PROGRAM

o o o

o o o o o o

o o o o

o o

o o o o o o o

o o o o o o

o o o o o o o

o o o o o o o

o o o o o

o o o o

C mplete pr grams will be discussed in the next secti n.

In this secti n we describe a task f r a r b t named Karel and a c mplete pr gram that instructs it t perf rm the task. The task, illustrated in Figure 2-3, is t transp rt the beeper fr m 1st Street and 4th Avenue t 3rd Street and 5th Avenue. After Karel has put d wn the beeper, it must m ve ne bl ck farther n rth bef re turning ff.

The f ll wing pr gram instructs Karel t perf rm this task. The pr gram uses all f the instructi ns available t r b ts in the class, a few new w rds fr m the r b t pr gramming v cabulary, and punctuati n symb ls such as the peri d and semic l n. We will first discuss Karel’s executi n f this pr gram, and then analyze the general structure f all r b t pr grams.

Karel.move(); Karel.move();

Karel.pickBeeper(); Karel.turnOff(); };

ur_Robot

task {

ur_Robot Karel(1, 2, East, 0); Karel.move();

Karel.move();

Karel.pickBeeper(); Karel.move();

Karel.turnLeft(); Karel.move(); Karel.move();

o o


(6)

2.6.1

Executing a Program

o o o o o o

o o o o o o

o

o o o o o o o o o

o o o o

o o o o o

o o o o

o o o

o o o o o o

o o o o o o

o o o o o

o o o o

o o o o o o

o o o o o

o o o

o o o o o

o o o o o o o

o o

o o

o o o o o o o

o o o o o

o o o o o o o

o o o o o o o o o o

o o o o o

o o o o o o

o o o o o o o

o o o o o

o o o

o o o o o o o o

o o o

o o o o o o

o o o o

o o o o o o o o o

o o o o o o

o o o o

We must n te that this is n t the nly sequence f instructi ns that will c rrectly perf rm the stated task. Alth ugh it is bvi us and direct, this is just ne f many sequences that will acc mplish the task.

A set f instructi ns f r ne r m re r b ts is called a and is intr duced by the special term, r reserved w rd, . The first instructi n in the main task bl ck c nstructs the r b t, ass ciates the name with it, and delivers it fr m the fac-t ry, ready fac-t run, fac-t 1sfac-t Sfac-treefac-t and 2nd Avenue, facing easfac-t wifac-th n beepers in ifac-ts beeper-bag. This statement can be th ught f as a delivery specificati n. It instructs the helic pter pil t h w t set up the r b t when it is delivered. The delivery specifi-cati n als names the specific type r class f r b t that we want delivered. Here we want an .

The remaining lines f the main task bl ck instruct Karel h w t carry ut the task. These instructi ns are read t Karel by the helic pter pil t, as described next.

Bef re a pr gram can be executed in a w rld, the pr gram is read at the fact ry t make sure it has n err rs. We will discuss err rs later; f r n w, we will assume that

ur pr gram is c rrect.

H w is a pr gram executed? A pr gram executi n is begun after the helic pter pil t delivers the r b t t the required c rner and sets it up acc rding t the delivery specificati n. Here we require that the be set up n 1st Street and 2nd Avenue, facing east, and with zer beepers in its beeper-bag. Then, f r each additi nal c mmand in the main task bl ck, the pil t sends a c rresp nding electr nic message t the r b t named in that c mmand. The message gives the instructi n that the named r b t is supp sed t perf rm. These messages are relayed by the pil t t the r b t thr ugh a special r b t c ntr l satellite that h vers ver the w rld. Since a r b t can execute nly ne instructi n at a time and since the satellite has a very limited c mmunicati n capacity, nly ne instructi n can be sent at a time. The pil t must wait f r instructi n c mpleti n bef re sending the next message. When the r b t c mpletes the current instructi n, it sends a reply back t the pil t thr ugh the satellite indicating that the next instructi n can be sent. Messages fr m the main task bl ck are sent sequentially with ut mitting any instructi ns in a strict t p-t -b tt m rder. The pil t c ntinues sending messages until either all messages in the main task bl ck have been sent r the pil t attempts t send a message t a r b t that has executed a

r has perf rmed an err r shut ff.

It is als p ssible f r r b ts t send messages t each ther. When this ccurs, the r b t sending the message waits f r the reply bef re c ntinuing. This is t guarantee that the satellite c mmunicati n channel is never verl aded.

task

Karel.putBeeper(); Karel.move(); Karel.turnOff(); }

task Karel

ur_Robot

ur_Robot Karel


(7)

o o o o o

o o o o o

o o o o o o

o o o o o o o

o o o o o o o o

o o o o o o

o o o o o o o o

o o o o o o o

o

o o o o o o o o o

o o o o

o o o o o o o

o o o o o o

o o o o o o o

o o o o o o

o o o o o o o

o o o

o o o o

T determine what a pr gram d es, we simulate, r trace, its executi n. Simulating r tracing a r b t pr gram means that we must systematically execute the pr gram exactly as the pil t and r b ts w uld, rec rding every acti n that takes place. We can simulate a r b t pr gram by using markers n a sheet f paper (representing r b ts and the w rld). We simulate a r b t pr gram by f ll wing the sequence f instructi ns in the rder the pil t reads them t the r b t. We will discuss tracing later, but in rder t bec me pr ficient r b t pr grammers, we must understand exactly h w the pil t reads the pr gram and the r b t executes it. The ability t simulate a r b t’s behavi r quickly and accurately is an imp rtant skill that we must acquire.

Let’s f ll w a simulati n f ur pr gram. In the f ll wing simulati n

means 1st Street and 4th Avenue. In the f ll wing ann tati n we explain exactly what state the r b t is left in after the executi n f the instructi n. N te that the symb l (tw adjacent slash characters) is used in the simulati n t intr duce c mments int

ur r b t pr grams. Each c mment begins with the mark and c ntinues t the end f the line. These c mments are ign red by the pil t and by the r b ts; they are included nly t aid ur wn understanding f the pr gram. Here we use them t explain in detail each instructi n as it will be executed. We n te, h wever, that if the pr gram is changed in any way, the c mments are likely t bec me invalid.

(1, 4) // //

task {

ur_Robot Karel(1, 2, East, 0);

// A new robot named Karel is // constructed and delivered to // (1, 2), facing East. Karel has // no beepers in its beeper-bag.

Karel.move(); // Karel moves east

// to (1, 3)

Karel.move(); // Karel moves east

// to (1, 4)

Karel.pickBeeper(); // Karel picks 1 beeper, // 1 beeper in bag

Karel.move(); // Karel moves east

// to (1, 5)

Karel.turnLeft(); // Karel remains on

// (1, 5), faces North

Karel.move(); // Karel moves north

// to (2, 5)

Karel.move; // Karel moves north

// to (3, 5)

Karel.putBeeper(); // Karel puts 1 beeper // down, now 0 beepers // in bag

Karel.move(); // Karel moves north


(8)

2.6.2

The Form of Robot Programs

o o o o o o

o o o

o o o o o o

o o o o o o o

o o o o

o o o o o o

o o o o o

o o o o o o o

o o o o

o o o o o

o o o o o

o o o o

o o o o

o o o o o o

o o o o o o o o o

o o o o o

o o o

o o o o

o o o o

o o o o o o o

o o o o

o o o o o o

o o o o o o

o o o o o

o o o o o o

o o o o

o o o o o o

o o o o o o o o o o o

o o o o

o o o

o o o

o o o

o o o o o o

o o o o o o o o o

o o o o

Karel is d ne and we have verified that ur pr gram is c rrect thr ugh simulati n by tracing the executi n f the pr gram.

N w that we have seen h w a r b t executes a pr gram, let’s expl re the grammar rules f the r b t pr gramming language. The fact ry and pil ts pay strict attenti n t grammar and punctuati n rules, s ur time is well spent carefully studying these rules. We start by dividing the symb ls in a r b t pr gram int three gr ups. The first gr up c nsists f special symb ls. It has members such as the punctuati n marks like the semic l n, the braces and , and the peri d. The next gr up f symb ls c nsists f names such as r b t and class names, and . We als use names t refer t instructi ns, like and . The third and last gr up f symb ls c nsists f reserved w rds. We have already seen a few f these like and .

Reserved w rds are used t structure and rganize the primitive instructi ns in the r b t pr gramming language. They are called w rds because their use is reserved f r their built-in purp se. These reserved w rds may n t be reused f r ther purp ses in a r b t pr gram, such as r b t names. T make the reading f pr grams easier, we may write r b t pr grams using b th upper- and l wercase letters as well as the undersc re character, but we must be c nsistent. F r example, is always spelled with all l wercase letters. The r b t pr gramming language is

meaning that the use f upper- and l wercase letters in a w rd must be c nsistent each time the w rd is used. If we use the w rd in a r b t pr gram it w uld refer t s mething else, perhaps the name f a r b t.

Since r b t pr grams need t be read by humans as well as r b ts, it is helpful t be able t put explanat ry material int the pr gram itself. The language theref re permits c mments t be inserted int the text f the pr gram. As we have seen in the f reg ing pr gram, a c mment begins anywhere n a line with the special symb l (tw slash marks with n space between). The c mment terminates nly when the line d es. Anything may be put n the line f ll wing the c mment symb l.

Every r b t pr gram c nsists f a single task f r ne r m re r b ts. This main task bl ck is intr duced by the reserved w rd and is encl sed in curly brace punctuati n marks. N tice that the pening brace must be matched eventually by a cl sing brace. Matching pairs f braces are called delimiters, because they mark, r delimit, the beginning and end f s me imp rtant entity.

If we needed specialized r b ts t perf rm vari us parts f the task, the class dec-larati ns f th se r b ts w uld precede the task list, as w uld the definiti ns f any new instructi ns named in the class declarati ns. We will g int this in detail in Chapter 3.

reserved

case-sensitive,

Karel.turnOff(); // Karel remains on

// (4, 5) facing North // and shuts off

}

{ }

Karel ur_Robot

putBeeper turnLeft

class task

task

Task

//


(9)

o o o o

o o o o o o

o o o o

o o o o

o o o o o o o o

o o o o o o o

o o o o o o o o

o o o o o o o o o

o o o o

o o o o o o

o o o o o o o

o o o o

o

o o o

o o o o o o

o o o o o o

o o o o o

o o o o

o o o o o o o

o o o o o o o

o o

o o o o o

o o o o o o o o o o

o

o o o

o o o o o

o o o o o

o o o o o o

o o o o

o o o o

o o o o

o o o o o

o o o o o o

o o o

o o o o o

o o o o

o o

o o o o

o o o

The main task bl ck itself starts with a list f definiti ns, called declarati ns. In the f ll wing pr gram we have nly ne declarati n, which declares that the name will be used as the name f a r b t in class . Declarati ns in-tr duce new names and indicate h w they will be used in the rest f the pr gram. The declarati ns f r b t names always end with a semic l n. We c uld als declare names f r several different r b ts, even r b ts f different classes. The declarati ns f r b ts can best be th ught f as delivery specificati ns t the fact ry. They always c ntain inf rmati n ab ut h w the r b t sh uld be placed in the w rld.

Every pr gram has ne main task bl ck. Each f the statements in the main task bl ck is terminated by a semic l n. M st f the statements in the main task bl ck are instructi ns t the r b ts declared in the declarati n list. The ne excepti n here is the delivery instructi n, which causes the fact ry t c nstruct and deliver a new named Karel t 1st Street and 2nd Avenue (we always list streets first), facing east, with n beepers in its beeper-bag. When delivered, the r b t is set up and ready t execute instructi ns sent t it. Since r b ts are delivered by the fact ry in helic pters, we d n’t need t be c ncerned ab ut walls in the w rld that might impede delivery t any c rner. The helic pter will be able t fly ver them.

Instructi ns given t a specific r b t are called messages. We can send messages t several different r b ts fr m the same main task bl ck, s we need t specify which r b t is t carry ut each instructi n. Thus, if we have a r b t named Karel and want it t m ve, we send the message . This seems redundant here when there is nly ne r b t, but it is required nevertheless. An instructi n that causes a r b t t perf rm ne f its wn instructi ns, such as m ve, is kn wn as a message statement. The instructi n named in a message statement ( ) is called the message, and the r b t ( ) is the receiver f the message. Messages are the means f getting a r b t t execute an instructi n.

Executi n always begins with the first instructi n f ll wing the reserved w rd . R b ts are aut matically shut d wn at the final cl sing brace in a pr gram; the instructi n must be used f r that purp se. The cl sing brace marks the end f the instructi ns that will be executed. If we reach the end f the instructi ns in the main task bl ck and any r b t is still n because it hasn’t yet executed a

instructi n, it means that at least ne instructi n has been mitted fr m the pr gram, and any r b t still n will rep rt an err r.

Observe that the pr gram is nicely indented as well as c mmented. It is well r-ganized and easy t read. This style f indenting, as well as the c mments, is nly f r the benefit f human readers. The f ll wing pr gram is just as easily executed as the previ us pr gram.

As this example illustrates, the imp rtance f ad pting a pr gramming style that is easy t read by humans cann t be veremphasized.

not Karel ur_Robot ur_Robot Karel.move() move Karel task turnOff turnOff turnOff

task { ur_Robot Karel(1,2, East,0); Karel.move(); Karel.move(); Karel.pickBeeper(); Karel.move(); Karel.turnLeft(); Karel.move(); Karel.move();


(10)

v

v

v

v

2.7

ERROR SHUTOFFS

2.8

PROGRAMMING ERRORS

o o o o o o

o o o o o o

o o o o o o

o o o o o

o o o

o o o o o o

o

o o o o o o

o o o o o o

o o o o o o o

o o o o o o

o o

o o o o o o

o o o o o o oo

o

o o o o

o o o

o o o o

o o o o o o

o o

o o o o o o

o

o o o o o

o o o o o

o o o o o

o o o o

o o o o o o o

o o o o o o

o o o o o

o o o o o o

o o o o o o o o

o o o o o

o o o o

o o o o o o o o

o o o o o

o o o o o o o

o o o o

When a r b t is prevented fr m successfully c mpleting the acti n ass ciated with an instructi n, it turns itself ff. This acti n is kn wn as an err r shut ff, and the effect is equivalent t executing a instructi n. H wever, turning ff is n t the nly way such a pr blem c uld be addressed. An alternative strategy c uld have the r b t just ign re any instructi n that cann t be executed successfully. Using this strategy the r b t c uld c ntinue executing the pr gram as if it had never been required t execute the unsuccessful instructi n.

T justify the ch ice f executing an err r shut ff, rather than just ign ring in-structi ns in such situati ns, c nsider the f ll wing: Once an unexpected situati n arises— ne that prevents successful executi n f an instructi n—a r b t pr bably will be unable t make further pr gress t ward acc mplishing the task. C ntinuing t execute a pr gram under these circumstances will lead t an even greater discrepancy between what the pr grammer had intended f r the r b t t d and what it is actually d ing. C nsequently, the best strategy is t have the r b t turn ff as s n as the first inc nsistency appears.

S far, we have seen three instructi ns that can cause err r shut ffs: , , and . We must c nstruct ur pr grams carefully and ensure that the f ll wing c nditi ns are always satisfied.

A r b t executes a instructi n nly when the path is clear t the next c rner immediately in fr nt f it.

A r b t executes a instructi n nly when it is n the same c rner as at least ne beeper.

A r b t executes a instructi n nly when the beeper-bag is n t empty.

A r b t executes a instructi n at the end f each pr gram.

We can guarantee that these c nditi ns are met if, bef re writing ur pr gram, we kn w the exact initial situati n in which the r b t will be placed.

In this secti n we classify all pr gramming err rs int f ur br ad categ ries. These categ ries are discussed using the anal gy f a m t rist with a task in the real w rld. It sh uld help clarify the nature f each err r type. Y u might ask, “Why spend s much time talking ab ut err rs when they sh uld never ccur?” The answer t this questi n is that pr gramming requires an unc mm n am unt f precisi n, and alth ugh err rs sh uld n t ccur in principle, they ccur excessively in practice. Theref re we must bec me adept at quickly finding and fixing err rs by simulating ur pr grams.

A lexical err r ccurs whenever the r b t pr gram c ntains a w rd that is n t in its v cabulary. As an anal gy, supp se that we are standing n a street in San Francisc and we are asked by a l st m t rist, “H w can I get t P rtland, Oreg n?” If we tell the m t rist, “fsdt jkhpy hqngrpz fgssj sgr ghhgh grmplhms,” we c mmit a lexical err r.

turnOff

move

pickBeeper putBeeper

move

pickBeeper putBeeper turnOff


(11)

o o o o o o o o o

o o o o o o o

o o o o

o o o o o

o o o o o

o o

o o o o o

o o o o o o o

o o o o o o o o o

o o o o o o o

o o o o

o o o o o o o

o o o o o

o o o o o o o o

The m t rist is unable t f ll w ur instructi ns because it is imp ssible t decipher the w rds f which the instructi ns are c mp sed. Similarly, the r b t executing a pr gram must understand each w rd in a pr gram that it is asked t execute.

Here is a r b t pr gram with s me lexical err rs:

The last err r ccurs because the r b t pr gramming language is case-sensitive. The w rd turnLeft is n t the same as turnleft.

Even if the pil t rec gnizes every w rd in a pr gram, the pr gram still might har-b r a syntax err r. This type f err r ccurs whenever we use inc rrect grammar r inc rrect punctuati n. G ing back t ur l st m t rist, we might reply, “f r, Keep hun-dred. just miles g ing eight.” Alth ugh the m t rist rec gnizes each f these w rds individually, we have c mbined them in a senseless, c nv luted manner. Acc rding t the rules f English grammar, the parts f speech are n t in their c rrect p siti ns. We discussed the grammar rules f r basic r b t pr grams in Secti n 2.6.2.

The f ll wing pr gram c ntains n lexical err rs, but it d es have syntax err rs.

taxt // misspelled reserved word

{

ur_Robot Karel(1,2, East, 0) ; Karel.move();

Karel.mvoe(); // misspelled instruction

Karel.pick(); // unknown word

Karel.move();

Karel.turnright(); // unknown word Karel.turnleft(); // unknown word Karel.move();

}

ur_Robot Karel(1,1,East,0); // declaration not in // main task block

task // missing brace

Karel.move();

move(); // not addressed

// to any robot

Karel.pickBeeper // no ()

Karel :: move(); // incorrect use of ::

Karel.turnLeft() // missing semicolon

Karel.move(); Karel.move();

Karel.put-beeper(); // use capitalization,

// not dash. Karel.move();

}; // extra semicolon

Karel.turnOff() // instruction outside

// task block and // missing semicolon


(12)

o o o o o o o

o o o o o o o o

o o o o o o o o

o o o o o o o o o

o o o o o o o

o o o o o

o o o o o o o o o

o o o

o o o o

o o o o o

o o o o o o o o

o o o o o

o o o o o o o o o o o

o o o o o o

o o o o

o o o o o

o o o o o o o o o

o o o o

o o o o o o

o o o o o o

o o o o

o o o o o o

o o o o o o o

o o o o o o o

o o o o o

o o o o o o o

o o o o

o o o o o o o o o

o

o o o o o o

o o o o o o o

o o o o o o o

o o o o o

o o o

If ur pr gram c ntains lexical r syntax err rs, the fact ry will disc ver them when ur pr gram is checked there. In b th cases, the fact ry has n c ncepti n f what we t say; theref re, it d es n t try t c rrect ur err rs. Instead, the fact ry inf rms us f the detected err rs and d esn’t build the r b t. This acti n is n t an err r shut ff, f r in this case the r b t never has a chance t begin t execute the pr gram. While discussing the next tw categ ries f err rs, we will assume that the fact ry finds n lexical r syntax err rs in ur pr gram, s it builds the r b t and the pil t delivers it and begins t execute the pr gram.

The third err r categ ry is called an executi n err r. Unlike lexical and syntax err rs, which are detected at the fact ry, the pil t can nly detect these err rs while the pr gram is running r during a simulati n f its executi n. Executi n err rs ccur whenever a r b t in the w rld is unable t execute an instructi n successfully and is f rced t perf rm an err r shut ff. Returning t ur m t rist, wh is trying t drive fr m San Francisc t P rtland, we might say, “Just keep g ing f r eight hundred miles.” But if the m t rist happens t be facing west at the time, and takes ur direc-ti ns literally, the m t rist w uld reach the Pacific Ocean after traveling nly a few miles. At this p int, the m t rist w uld halt, realizing that he r she cann t f ll w ur instructi ns t c mpleti n.

Likewise, a r b t turns ff if asked t execute an instructi n that it cann t execute successfully. Instructing a r b t t when the fr nt is bl cked, t

n a c rner that has n beeper, and t when the beeper-bag is empty are examples f executi n err rs, and each ne results in an err r shut ff.

The final err r class is the m st insidi us, because pil ts, the fact ry, and r b ts cann t detect this type f err r when it ccurs. We label this categ ry f err r an intent err r. An intent err r ccurs whenever the pr gram successfully terminates but d es n t successfully c mplete the task. Supp se ur m t rist is facing s uth when we say, “Just keep g ing f r eight hundred miles.” Even th ugh these instructi ns can be successfully f ll wed t c mpleti n, the m t rist will end up s mewhere in Mexic , rather than Oreg n.

Here is an example f an intent err r in a r b t pr gram: Beginning in the situati n sh wn in Figure 2-4, Karel is t pick up the beeper, m ve it ne bl ck t the n rth, put the beeper d wn, m ve ne m re bl ck t the n rth, and .

There are n lexical, syntax, r executi n err rs in this pr gram. As far as Karel and the helic pter pil t are c ncerned, when the is executed, everything is

meant

move pickBeeper

putBeeper

turnOff task

{ ur_Robot Karel(3,2, East, 0); Karel.move();

Karel.pickBeeper(); Karel.move();

Karel.turnLeft(); Karel.putBeeper(); Karel.move(); Karel.turnOff(); }


(13)

Figure 2-4

2.8.1

Bugs and Debugging

2.9

PROBLEM SET

o oo oo o o

o o o o o o o o o o

o o o

o o o o o

o o

o o o o o o

o o o o o

o o o o o o o o o o

o o o o

o o o o

o o o o o o

o o o o o o o

o o o o o o o o

o o o o o o o

o o

o o o oo

o o o o o o o

o o o o o

o o o o o o

o o o o

o o o o o o

o o

o o o o o

o o o o

o o o o o o o

o o o o o o o o o

o o o o o o o o o

perfect. H wever, l k at the task and l k at the pr gram. What is the err r? The task is t m ve the beeper ne bl ck t the n rth, yet Karel m ved the beeper ne bl ck t the east. The intent was a n rtherly m ve, but the final result was an easterly m ve. The pr gram d es n t satisfy the requirements f the stated task and thus c ntains an err r f intent.

Remember that a r b t d es n t understand the task f r which we have pr -grammed it. All that the r b t can d is execute the instructi ns we have sent it in ur pr gram. Thus, there is n way f r a r b t t kn w that the pr gram did n t acc m-plish what we intended. Similarly, the pil t has n way t kn w what we intended. He r she nly kn ws what is actually written in the pr gram itself.

In pr gramming jarg n, all types f err rs are kn wn as bugs. There are many ap c-ryphal st ries ab ut the rigin f this term. In ne st ry the term is said t have been riginated by teleph ne c mpany engineers t refer t the s urce f rand m n ises transmitted by their electr nic c mmunicati ns circuits. An ther st ry rigi-nated with the Harvard Mark I C mputer and Grace Murray H pper, later Admiral. The c mputer was pr ducing inc rrect answers, and when engineers t k it apart try-ing t l cate the pr blem, they f und a dead m th caught between the c ntacts f a relay, causing the malfuncti n: the first c mputer bug. Other st ries ab und, s per-haps we shall never kn w the true ent m l gy f this w rd.

Perhaps the term became p pular in pr gramming because it saved the eg s f pr grammers. Instead f admitting that their pr grams were full f err rs, they c uld say that their pr grams had bugs in them. Actually, the metaph r is apt; bugs are hard t find, and alth ugh a l cated bug is frequently easy t fix, it is difficult t ensure that all bugs have been f und and rem ved fr m a pr gram. Debugging is the name that pr grammers give t the activity f rem ving err rs fr m a pr gram.

The purp se f this pr blem set is t test y ur kn wledge f the f rm and c ntent f simple r b t pr grams. The pr grams y u are required t write are l ng but n t

bug

bug

o Karel’s Initial Situati n


(14)

Figure 2-5

o o o o o

o o o o o

o o o o o o o

o o

o o o o o o o

o o o o

o

o o o

o o o o o o

o o o

o o o o o o o o o

o o o o o o o

c mplicated. C ncentrate n writing grammatically c rrect, pleasingly styled pr -grams. Refer back t the pr gram and discussi n in Secti n 2.6 f r rules and examples f c rrect grammar and punctuati n. Each f these pr blems requires a single r b t f the class. In each case we assume it will be named Karel. This is n t required, h wever, and y u are, in general, free t name y ur r b ts with ther names. Verify that each pr gram is c rrect by simulating Karel’s acti ns in the appr priate initial situati n.

Start a r b t in the initial situati n illustrated in Figure 2-5 and simulate the executi n f the f ll wing pr gram. Karel’s task is t find the beeper, pick it up, and then turn itself ff. Draw a map f the final situati n, stating whether an err r ccurs. If an executi n r intent err r d es ccur, explain h w y u w uld c rrect the pr gram. This pr gram has n lexical r syntactic err rs.

1.

ur_Robot

task

{ ur_Robot Karel(2, 7, West, 0); Karel.move();

Karel.turnLeft(); Karel.turnLeft(); Karel.move(); Karel.turnLeft(); Karel.move(); Karel.turnLeft(); Karel.move();

Karel.pickBeeper(); Karel.turnOff(); }

o o o


(15)

Figure 2-6

o o o o

o o o o o o o

o o o oo o

o o o o

o o o o o o o

o o

o o o o

o o o o o

o o o

o o

o o

Carefully inspect the f ll wing pr gram and c rrect all lexical and syntactic err rs. There are nine err rs. F ur err rs inv lve semic l ns, three are syntactical, and ne is lexical. (Yes, there is an ther err r t .) C nfirm that each w rd is in an appr priate place and that it is a c rrectly spelled instructi n name r reserved w rd. Y u may use the pr gram in Pr blem 1 as a m del f r a lexically and syntactically c rrect pr gram.

What is the smallest lexically and syntactically c rrect r b t pr gram? In m st cities and t wns we can walk ar und the bl ck by repeating the f l-l wing acti ns f ur times:

Walk t the nearest intersecti n

Turn either right r left (the same ne each time)

2.

3. 4.

Hint:

task

{ ur_Robot Karel(2,7, East, 0); Karel.move();

Karel.move()

Karel.pickBeeper(); Karel.move;(); Karel.turnLeft(); move();

Karel.move(); Karel.turnright; Karel.putBeeper(); Karel.putBeeper(); Karel.turnOff };

o o o o

Initial Situati n f r the Walk-Ar und-the-Bl ck Task


(16)

Figure 2-7

o o o o o o

o o o o o o

o o

o o o o o o o o

o o

o o

o

o o o o

o o o

o o o

o o o o o o o

o o o o o

o o o

If this is d ne c rrectly, we will return t ur riginal starting place. Pr gram Karel t walk ar und the bl ck. Will y ur pr gram succeed f r the initial sit-uati n in Figure 2-6?

Every m rning Karel is awakened in bed when the newspaper, represented by a beeper, is thr wn n the fr nt p rch f the h use. Pr gram Karel t retrieve the paper and bring it back t bed. The initial situati n is given in Figure 2-7, and the final situati n must have Karel back in bed (same c rner, same directi n) with the newspaper.

The wall secti ns in Figure 2-8 represent a m untain (n rth is up). Pr gram Karel t climb the m untain and then plant a flag, represented by a beeper, n the summit; Karel then must descend the ther side f the m untain. Assume that Karel starts with the flag-beeper in the beeper-bag. Remember that Karel is n t a super-r b t that can leap t the t p f the m untain, plant the flag, and then jump d wn in a single b und. As illustrated, Karel must cl sely f ll w the m untain’s face n the way up and d wn.

5.

6.

o o

Initial Situati n f r the Newspaper Retrieval Task


(17)

Figure 2-8

Figure 2-9

o o o

o o o

o o o

o o o

o o o

On the way h me fr m the supermarket, Karel’s sh pping bag ripped slightly at the b tt m, leaking a few expensive items. These gr ceries are represented by—y u guessed it—beepers. The initial situati n, when Karel disc vered the leak, is represented in Figure 2-9. Pr gram Karel t pick up all the dr pped items and then return t the starting p siti n.

7.

o

o o o

The M untain Climbing Task


(18)

Figure 2-10

Figure 2-11

o o o

o o o o

o o o o

o o o

o o

o o

o

Write a pr gram that instructs Karel t rearrange the beeper pattern as sh wn in Figure 2-10.

Karel is practicing f r the R b t Olympics. One f Karel’s events is the shuttle race. The shuttle race requires Karel t m ve ar und tw beepers in a figure 8 pattern as sh wn in Figure 2-11. Write a pr gram that instructs Karel t walk a figure 8 pattern as fast as p ssible (“fast” implies as few instructi ns as p ssible). Karel must st p in the same place it starts and must be facing the same directi n.

8.

9.

The Rearrange-the-Beepers Task


(1)

Figure 2-4

2.8.1

Bugs and Debugging

2.9

PROBLEM SET

o oo oo o o

o o o o o o o o o o

o o o

o o o o o

o o

o o o o o o

o o o o o

o o o o o o o o o o

o o o o

o o o o

o o o o o o

o o o o o o o

o o o o o o o o

o o o o o o o

o o

o o o oo

o o o o o o o

o o o o o

o o o o o o

o o o o

o o o o o o

o o

o o o o o

o o o o

o o o o o o o

o o o o o o o o o

o o o o o o o o o

perfect. H wever, l k at the task and l k at the pr gram. What is the err r? The task is t m ve the beeper ne bl ck t the n rth, yet Karel m ved the beeper ne bl ck t the east. The intent was a n rtherly m ve, but the final result was an easterly m ve. The pr gram d es n t satisfy the requirements f the stated task and thus c ntains an err r f intent.

Remember that a r b t d es n t understand the task f r which we have pr -grammed it. All that the r b t can d is execute the instructi ns we have sent it in ur pr gram. Thus, there is n way f r a r b t t kn w that the pr gram did n t acc m-plish what we intended. Similarly, the pil t has n way t kn w what we intended. He r she nly kn ws what is actually written in the pr gram itself.

In pr gramming jarg n, all types f err rs are kn wn as bugs. There are many ap c-ryphal st ries ab ut the rigin f this term. In ne st ry the term is said t have been riginated by teleph ne c mpany engineers t refer t the s urce f rand m n ises transmitted by their electr nic c mmunicati ns circuits. An ther st ry rigi-nated with the Harvard Mark I C mputer and Grace Murray H pper, later Admiral. The c mputer was pr ducing inc rrect answers, and when engineers t k it apart try-ing t l cate the pr blem, they f und a dead m th caught between the c ntacts f a relay, causing the malfuncti n: the first c mputer bug. Other st ries ab und, s per-haps we shall never kn w the true ent m l gy f this w rd.

Perhaps the term became p pular in pr gramming because it saved the eg s f pr grammers. Instead f admitting that their pr grams were full f err rs, they c uld say that their pr grams had bugs in them. Actually, the metaph r is apt; bugs are hard t find, and alth ugh a l cated bug is frequently easy t fix, it is difficult t ensure that all bugs have been f und and rem ved fr m a pr gram. Debugging is the name that pr grammers give t the activity f rem ving err rs fr m a pr gram.

The purp se f this pr blem set is t test y ur kn wledge f the f rm and c ntent f simple r b t pr grams. The pr grams y u are required t write are l ng but n t

bug

bug

o Karel’s Initial Situati n


(2)

Figure 2-5

o o o o o

o o o o o

o o o o o o o

o o

o o o o o o o

o o o o

o

o o o

o o o o o o

o o o

o o o o o o o o o

o o o o o o o

c mplicated. C ncentrate n writing grammatically c rrect, pleasingly styled pr -grams. Refer back t the pr gram and discussi n in Secti n 2.6 f r rules and examples f c rrect grammar and punctuati n. Each f these pr blems requires a single r b t f the class. In each case we assume it will be named Karel. This is n t required, h wever, and y u are, in general, free t name y ur r b ts with ther names. Verify that each pr gram is c rrect by simulating Karel’s acti ns in the appr priate initial situati n.

Start a r b t in the initial situati n illustrated in Figure 2-5 and simulate the executi n f the f ll wing pr gram. Karel’s task is t find the beeper, pick it up, and then turn itself ff. Draw a map f the final situati n, stating whether an err r ccurs. If an executi n r intent err r d es ccur, explain h w y u w uld c rrect the pr gram. This pr gram has n lexical r syntactic err rs.

1.

ur_Robot

task

{ ur_Robot Karel(2, 7, West, 0); Karel.move();

Karel.turnLeft(); Karel.turnLeft(); Karel.move(); Karel.turnLeft(); Karel.move(); Karel.turnLeft(); Karel.move();

Karel.pickBeeper(); Karel.turnOff(); }

o o o Initial Situati n f r Pr blem 1


(3)

Figure 2-6

o o o o

o o o o o o o

o o o oo o

o o o o

o o o o o o o

o o

o o o o

o o o o o

o o o

o o

o o

Carefully inspect the f ll wing pr gram and c rrect all lexical and syntactic err rs. There are nine err rs. F ur err rs inv lve semic l ns, three are syntactical, and ne is lexical. (Yes, there is an ther err r t .) C nfirm that each w rd is in an appr priate place and that it is a c rrectly spelled instructi n name r reserved w rd. Y u may use the pr gram in Pr blem 1 as a m del f r a lexically and syntactically c rrect pr gram.

What is the smallest lexically and syntactically c rrect r b t pr gram? In m st cities and t wns we can walk ar und the bl ck by repeating the f l-l wing acti ns f ur times:

Walk t the nearest intersecti n

Turn either right r left (the same ne each time)

2.

3. 4.

Hint:

task

{ ur_Robot Karel(2,7, East, 0); Karel.move();

Karel.move()

Karel.pickBeeper(); Karel.move;(); Karel.turnLeft(); move();

Karel.move(); Karel.turnright; Karel.putBeeper(); Karel.putBeeper(); Karel.turnOff };

o o o o

Initial Situati n f r the Walk-Ar und-the-Bl ck Task


(4)

Figure 2-7

o o o o o o

o o o o o o

o o

o o o o o o o o

o o

o o

o

o o o o

o o o

o o o

o o o o o o o

o o o o o

o o o

If this is d ne c rrectly, we will return t ur riginal starting place. Pr gram Karel t walk ar und the bl ck. Will y ur pr gram succeed f r the initial sit-uati n in Figure 2-6?

Every m rning Karel is awakened in bed when the newspaper, represented by a beeper, is thr wn n the fr nt p rch f the h use. Pr gram Karel t retrieve the paper and bring it back t bed. The initial situati n is given in Figure 2-7, and the final situati n must have Karel back in bed (same c rner, same directi n) with the newspaper.

The wall secti ns in Figure 2-8 represent a m untain (n rth is up). Pr gram Karel t climb the m untain and then plant a flag, represented by a beeper, n the summit; Karel then must descend the ther side f the m untain. Assume that Karel starts with the flag-beeper in the beeper-bag. Remember that Karel is n t a super-r b t that can leap t the t p f the m untain, plant the flag, and then jump d wn in a single b und. As illustrated, Karel must cl sely f ll w the m untain’s face n the way up and d wn.

5.

6.

o o

Initial Situati n f r the Newspaper Retrieval Task


(5)

Figure 2-8

Figure 2-9

o o o

o o o

o o o

o o o

o o o

On the way h me fr m the supermarket, Karel’s sh pping bag ripped slightly at the b tt m, leaking a few expensive items. These gr ceries are represented by—y u guessed it—beepers. The initial situati n, when Karel disc vered the leak, is represented in Figure 2-9. Pr gram Karel t pick up all the dr pped items and then return t the starting p siti n.

7.

o

o o o

The M untain Climbing Task


(6)

Figure 2-10

Figure 2-11

o o o

o o o o

o o o o

o o o

o o

o o

o

Write a pr gram that instructs Karel t rearrange the beeper pattern as sh wn in Figure 2-10.

Karel is practicing f r the R b t Olympics. One f Karel’s events is the shuttle race. The shuttle race requires Karel t m ve ar und tw beepers in a figure 8 pattern as sh wn in Figure 2-11. Write a pr gram that instructs Karel t walk a figure 8 pattern as fast as p ssible (“fast” implies as few instructi ns as p ssible). Karel must st p in the same place it starts and must be facing the same directi n.

8.

9.

The Rearrange-the-Beepers Task