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.

32<br />

numeric done[][], i, j, n ; n := 0 ;<br />

forever :<br />

i := round(uniformdeviate(10)) ; j := round(uniformdeviate(2)) ;<br />

if unknown done[i][j] :<br />

drawdot (i*cm,j*cm) ; n := n + 1 ; done[i][j] := n ;<br />

fi ;<br />

exitif n = 10 ;<br />

endfor ;<br />

Here we remain in the loop until we have 10 points placed. We use an array to keep track of placed<br />

points. The METAPOST macro uniformdeviate(n) returns a random number between 0 and n and<br />

the round command is used to move the result toward the nearest integer. The unknown primitive<br />

allows us to test if the array element already exists, otherwise we exit the conditional. This saves<br />

a bit of computational time as each point is drawn and indexed only once.<br />

The loop terminator exitif and its companion exitunless can be used in for, forsuffixes and<br />

forever.<br />

1.9 Macros<br />

In the previous section we introduced upto. Actually this is not part of the built in syntax, but a<br />

sort of shortcut, defined by:<br />

def upto = step 1 until enddef ;<br />

You just saw a macro definition where upto is the name of the macro. The counterpart of upto<br />

is downto. Whenever you use upto, it is replaced by step 1 until. This replacement is called<br />

expansion.<br />

There are several types of macros. A primary macro is used to define your own operators. For<br />

example:<br />

primarydef p doublescaled s =<br />

p xscaled (s/2) yscaled (s*2)<br />

enddef ;<br />

Once defined, the doublescaled macro is implemented as in the following example:<br />

draw somepath doublescaled 2cm withcolor red ;<br />

When this command is executed, the macro is expanded. Thus, the actual content of this command<br />

becomes:<br />

draw somepath xscaled 1cm yscaled 4cm withcolor red ;<br />

Welcome to MetaPost Macros

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

Saved successfully!

Ooh no, something went wrong!