Download Learning METAPOST by Doing
Transcript
Learning MetaPost by doing
VOORJAAR 2005
However, when you use the conditional clause to build up a single statement, then
you must be more careful with placing or omitting semicolons. In
draw p withcolor if cycle(p): red else: blue fi withpen pensquare;
you cannot add semicolons after the colour specifications, nor omit the final semicolon that marks the end of the statement (unless it is a statement that is recognised
as finished because of another keyword, e.g., endfor).
Repetition
Numerous examples in previous section have used the for loop of the form
for counter = start step stepsize until finish :
loop text
endfor;
where counter is a counting variable with initial value start. The counter is incremented at each step in the repetition by the value of stepsize until it passes the
value of finish. Then the repetition stops and METAPOST continues with what
comes after the endfor part. The loop text is usually any valid METAPOST statement or sequence of statements separated by semicolons that are executed at each
step in the repetition. Instead of step 1 until, we can also use the keyword upto.
downto is another word for step -1 until. This counted for loop is an example
of an unconditional repetition, in which a predetermined set of actions are carried
out. Below, we give another example of a counted for loop: generating a Bernoulli
walk. We use the normaldeviate operator to generate a random number with the
standard normal distribution (mean 0 and standard deviation 1).
beginfig(1);
n := 60; pair p[]; p0 = (0,0);
for i=1 upto n:
p[i] = p[i-1] +
(3,if normaldeviate>0: -3 else: 3 fi);
endfor;
draw p0 for i=1 upto n: --p[i] endfor;
endfig;
end;
The last example in the previous section, in which we computed the centre of gravity of randomly generated weighted points, contained another unconditional repetition, viz., the for loop over a sequence of zero or more expressions separated by
commas. Another example of this kind is:
(80,120)
(20,100)
beginfig(1);
fill for p=(0,0),(40,0),(80,120),(20,100):
p-- endfor cycle withcolor 0.8white;
for p=(0,0),(40,0),(80,120),(20,100):
dotlabel.bot("(" & decimal(xpart(p)) &
"," & decimal(ypart(p)) & ")", p);
endfor;
endfig;
end;
(0,0)
(40,0)
Nesting of counted for loops is of course possible, but there are no abbreviations:
balancing with respect to for and endfor is obligatory. You must use both endfor
keywords in
37