Functions |
To teach Karel new functions (instructions) we define these new functions in terms of functions that Karel already knows or has learned. In a sense, user-defined functions allow us to create a dictionary consisting of new words that Karel can recognize. Like in a dictionary, these new words are accompanied by a definition of the new function. To illustrate how this is done, let us see what a user-defined TurnRight() function definition looks like:
void TurnRight() { TurnLeft(); TurnLeft(); TurnLeft(); }If we insert this definition in a Karel program, we can use the TurnRight() instruction in directing Karel what to do. In other words, we have now taught Karel to turn right by executing three left turns. Note that TurnRight() for Karel means exactly what the instructions between the left and right curly braces say. The fact that TurnRight has somewhat of a meaning in the English language is of no concern to Karel. We could have defined:
void SelfDestruct() { TurnLeft(); TurnLeft(); TurnLeft(); }If Karel was asked to execute the SelfDestruct() instruction he would of course not explode or destroy himself, but rather would make three left turns.
IDENTIFIERS: The name of a function is called an identifier. An identifier consists of the following characters: A-Z, a-z, 0-9, and the underscore. The identifier cannot contain any blanks and must begin with an alphabetic letter. (Actually, it can begin with an underscore, but there are circumstances where this can cause problems so it is best not to do so.)
Karel is supposed to climb stairs and pick up the beepers on each step. When he is done, he should be standing on the top step, facing East.
|
// A Stair Cleaning Program #include <karel.h> using namespace std; // Pivot Karel 90 degrees to right. void TurnRight() { TurnLeft(); TurnLeft(); TurnLeft(); } // Climb on to next step. void ClimbAStep() { TurnLeft(); Move(); TurnRight(); Move(); } int main() { TurnOn(); ClimbAStep(); PickBeeper(); ClimbAStep(); PickBeeper(); ClimbAStep(); PickBeeper(); TurnOff(); } |
Example:
During the summer Karel works as a field laborer. His task is to harvest the field of beepers. He can relax and turn off as soon as he has harvested all beepers. |
Program 1 | Program 2 |
#include <karel.h> using namespace std; int main() { TurnOn(); Move(); PickBeeper(); Move(); PickBeeper(); ... TurnLeft(); Move(); TurnLeft(); PickBeeper(); Move(); ... TurnLeft(); TurnLeft(); TurnLeft(); Move(); TurnLeft(); TurnLeft(); TurnLeft(); PickBeeper(); Move(); ... TurnOff(); } |
#include <karel.h> using namespace std; int main() { TurnOn(); Move(); Harvest2Rows(); PositionForNextHarvest(); Harvest2Rows(); PositionForNextHarvest(); Harvest2Rows(); Move(); TurnOff(); } |
Program 1 Critique | Program 2 Critique |