XLOGO has seven primitives which allow the construction of loops: repeat, for , while, foreach, forever,
repeatwhile and repeatuntil.
repeat n list_of_commands |
|
n is a whole number and list_of_commands is a list containing the commands to execute. The LOGO interpreter
will implement the commands in the list n times: that avoids the need to copy the same command n
times!
Eg:
repeat 4 [forward 100 left 90] # A square of side 100
repeat 6 [forward 100 left 60] # A hexagon of side 100
repeat 360 [forward 2 left 1] # A uh... 360-gon of side 2
# In short, almost a circle!
Included in a repeat loop. Its an internal variable. Returns the number of the running iteration. (The first iteration
is number 1).
repeat 3 [pr repcount]
1
2
3
for assigns to a variable some successive values in a fixed range with a choosen increment.
list1 contains three arguments: the variable name, the start value, the end value.
A fourth argument is optionnal representing the increment (the step between two successive values). Default value is
1. Here are a few examples:
for [i 1 4][pr :i*2]
2
4
6
8
# Now, i is going from 7 to 2 falling down of 1.5 each times
# Look at the negative increment
# Then, Displays its square.
for [i 7 2 -1.5 ][pr list :i power :i 2]
7 49
5.5 30.25
4 16
2.5 6.25
while list_to_evaluate list_of_commands |
|
list_to_evaluate is a list containing an instruction set which can be evaluated as a boolean. list_of_commands is a
list containing the commands to execute. The LOGO interpreter will continue implementing the list_of_commands
so long as the list_to_evaluate is returned as true.
Eg:
while ["true] [rt 1] # The turtle will turn around
# An example which allows us to spell the alphabet in reverse
make "list "abcdefghijklmnopqrstuvwxyz
while [not empty? :list] [pr last :list make "list butlast :list]
foreach variable_name arg1 instructions |
|
The variable has for successive value the item from a list, or the character from a word. The instructions are
repeated for each value of the variable.
foreach "i "XLOGO [print :i]
X
L
O
G
O
foreach "i [a b c] [print :i]
a
b
c
make "sum 0 foreach "i 12345 [make "sum :sum+:i] print :sum
15
forever instructions_list |
|
Repeats forever a block of instructions waiting for a command to stop the loop.
Eg: forever [fd 1 rt 1]
Be careful when you use this primitive because of the infinite loop!
repeatwhile dowhile list1 list2 |
|
Repeats a block of instructions contained in list1 while list2 is true.
The main difference with the primitive while is that the bloack of instructions is at least executed one times even if
list2 is false.
make "i 0
repeatwhile [pr :i make "i :i+1] [:i<4]
0
1
2
3
4
repeatuntil dountil list1 list2 |
|
Repeats a block of instructions contained in list1 until list2 will be true.
make "i 0
repeatuntil [pr :i make "i :i+1] [:i>4]
0
1
2
3
4