procedure name(par1,
par2, ... , parN){...instructions...}
defines a new procedure with the name you want. The procedure can have zero
or more parameters, which you may also give useful names. Here they are called
par1, par2, . . . , parN. These are the variables you can use in the instruction
between curly brackets. The code in a procedure will not be performed automatically,
you have to write a 'procedure call' every time you want to perform the instructions
in the definition (See next instruction).
Tip: create a new procedure when when you you use a sequence
of instructions more than once.
Example:
# define how to draw a rectangle
procedure rectangle(width, height)
{
paintWhite
repeat(2)
{
forward(height)
right
forward(width)
right
}
stopPainting
}
name(arg1, arg2, . .
. , argN)
is the call to the procedure with the corresponding name and the same amount
parameters as you have arguments. The argument, here called arg1, arg2, . .
. , argN, are the particular values that will be used in the procedure definition.
Example:
# these instructions will be performed
forward(1)
rectangle(3,2) # a call to the 'rectangle' procedure
forward(3)
rectangle(1,4) # another call with other arguments
# this is the definition of 'rectangle'
procedure rectangle(width, height)
{
paintWhite
repeat(2)
{
forward(height)
right
forward(width)
right
}
stopPainting
}
return
To stop executing a procedure before it reaches the end, use return from within a
procedure definition. The program continues executing the commands after the corresponding call.
Example:
# these instructions will be performed
toWall()
right
forward
# go forward until you reach a wall
procedure toWall()
{
repeat
{
if(frontIsObstacle)
{
# stop "toWall" procedure,
# continue with right and forward
return
}
else{
forward
}
}
}
return(arg)
To stop executing a procedure before it reaches the end, use return from within a
procedure definition. The program continues executing the commands after the corresponding call.
By default, a procedure return the value zero. You can change this by returning an expression.
Example:
# this instruction will be performed
forward(double(3))
# double the given amount
procedure double(n)
{
return(2 * n)
}
Recursion
Procedures can be defined recursively. That means that you use the procedure you are defining in the procedure definition itself, by calling it.
It takes a while to comprehend, but turns out to be a powerfull tool.
Example:
# these instructions will be performed
toWall()
right
forward
# go forward until you reach a wall
procedure toWall()
{
# notice that no loops are used
if(frontIsObstacle)
{
# stop "toWall" procedure
return
}
else{
# do one step
forward
# and do a recursive call!
toWall()
}
}
|