29.11.2012 Views

MetaFun - Pragma ADE

MetaFun - Pragma ADE

MetaFun - Pragma ADE

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

1.8 Loops<br />

Yet another programming concept present in METAPOST is the loop statement, the familiar ‘for loop'<br />

of all programming languages.<br />

for i=0 step 2 until 20 :<br />

draw (0,i) ;<br />

endfor ;<br />

As explained convincingly in Niklaus Wirth's book on algorithms and datastructures, the for loop<br />

is the natural companion to an array. Given an array of length n, you can construct a path out of<br />

the points that make up the array.<br />

draw for i=0 step 1 until n-1 : p[i] .. endfor p[n] ;<br />

If the step increment is not explicitly stated, it has an assumed value of 1. We can shorten the<br />

previous loop construct as follows:<br />

draw for i=0 upto n-1 : p[i] .. endfor p[n] ;<br />

After seeing if in action, the following for loop will be no surprise:<br />

draw origin for i=0 step 10 until 100 : ..{down}(i,0) endfor ;<br />

This gives the zig--zag curve:<br />

You can use a loop to iterate over a list of objects. A simple 3--step iteration is:<br />

for i=p,q,r :<br />

fill i withcolor .8white ;<br />

draw i withcolor red ;<br />

endfor ;<br />

Using for in this manner can sometimes save a bit of typing. The list can contain any expression,<br />

and may be of different types.<br />

In the previous example the i is an independent variable, local to the for loop. If you want to<br />

change the loop variable itself, you need to use forsuffixes. In the next loop the paths p, q and r<br />

are all shifted.<br />

forsuffixes i = p, q, r :<br />

i := i shifted (3cm,2cm) ;<br />

endfor ;<br />

Sometimes you may want to loop forever until a specific condition occurs. For this, METAPOST<br />

provides a special looping mechanism:<br />

Loops Welcome to MetaPost<br />

31

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!