Loop structures: Difference between revisions

Content added Content deleted
No edit summary
Line 55: Line 55:
set i to 5
set i to 5
repeat until i is less than 0
repeat until i is less than 0
set i to i - 1
set i to i - 1
end repeat
end repeat


repeat
repeat
--endless loop
--endless loop
end repeat
end repeat


Line 620: Line 620:
echo $key.' is '.$value;
echo $key.' is '.$value;
}
}

==[[Pop11]]==
[[Category:Pop11]]

=== while ===
Pop11 offers multiple looping constructs. Basic one is while loop:

5 -> n;
while n > 0 do
printf(n, '%p\n');
n - 1 -> n;
endwhile;

=== until ===
Variant of while is until loop:

until condition do /* Action */ enduntil;

is equivalent to:

while mot(condition) do /* Action */ endwhile;

=== for ===
One can process all elements of a list:

for x in [a b c] do x => endfor;

It is possible to simultaneously process multiple lists:

for x y in [a b c], [1 2 3] do [^x ^y] => endfor;

in first iteration sets x to "a" and y to 1, in the second x is "b"
and y is 2, in the third (last) iteration x is "c" and y is 3.
The iteration ends when the shortest list is exhausted.

Somtimes one wants to process tails of the list, to do this use
on keyword instead of in keyword:

for x on [a b c] do x => endfor;

in first iteration sets x to [a b c], in the second to [b c], etc...

There is also "counting" version of for loop:

for x from 2 by 2 to 7 do x => endfor;

goes trough 2, 4 and 6. Ommited by frase means by 1.

There is alse a C-like for loop:

for action1 step action2 till condition do /* Actions */ endfor;

is equivalent to

action1
while not(condition) do
/* Actions */
action2
endwhile;

There are more specialized kinds of loops, but we skip them here.

=== quitloop quitif quitunless ===
Inside loops one can use control transfers to prematuraly exit the
loop or end current iteration and start the next one:

while true do n - 1 -> n; quitif(n=0); endwhile;

quits loop when n=0. quitloop unconditionally quits loop,
quitunless(x) is equivalent to quitif(not(x)).

=== nextloop nextif nextunless ===
Similarely to quitloop nextloop unconditionally ends current iteration
and starts the new one, nextif(x) ends current iteration when x is true,
nextunless(x) is equivalent to nextif(not(x)). The loop control transfers
can be also used inside for (and until) loops.

Finally, it is frequently possible to avoid explicit iteration
using higher order map functions (like appdata and mapdata).


==[[PostScript]]==
==[[PostScript]]==