# [metapost] Function defined by a sum

Dan Luecking luecking at uark.edu
Sun Nov 4 21:39:23 CET 2007

```At 05:46 AM 11/2/2007, you wrote:
>Le Fri, 2 Nov 2007 11:21:19 +0100 "Mojca Miklavec"
><mojca.miklavec.lists at gmail.com> a écrit :
>
> > There is no "sum" (unless you define one), but oyu can use "for" loop:
> >
> > vardef sin(expr xx) = sind(xx*180/3.14) enddef;
> >
> > vardef f(expr xx,n) =
> >    save sum;
> >    sum:=0;
> >    for i=1 upto n:
> >       sum := sum+sin(i*(xx))/i;
> >    endfor;
> >
> >    sum
> > enddef;
> >
> > beginfig(1);
> >    path p;
> >    p := (0,0)
> >    for j=1 upto 700:
> >       --(j/100,f(j/100,3))
> >    endfor;
> >    draw p scaled 1cm;
> > endfig;
> > end.

OR:
beginfig(1);
draw (0,0)
for j=1 upto 700:
--(j/100,f(j/100,3))
endfor;
endfig;

>Thanks. Someone on another list gave me something more "TeXish" :
>
>vardef sum_sin(expr x,n)=
>   0
>   for k:=1 upto n:
>     + sin(k*x)/x
>     endfor
>enddef;
>
>I thought something like this could work. But I don't know exactly why.
>Is this something like "token replacement", like in TeX ?

The index (k) of the for-loop is replaced by an internal token
which Knuth calls a "capsule" (think of it like TeX's #1, except
that any expression after "k:= " is first evaluated and its
value is used). When the for-loop is expanded, MP expands the
contents essentially as a token list, which it evaluates as it
goes. Thus, for k=1 we get:

0 + sin (1*x)/x [rest of the loop]

MP evaluates the sum and then resumes processing the loop
with k=2:

[value of sin (x)/x] + sin(2*x)/x [rest of the loop]
[value of sin(x)/x+sin(2*x)/x] + sin(3*x)/x [rest of the loop]

etc. MP really behaves a lot like TeX in this respect,
with for-loops behaving somewhat like conditionals in TeX.
If it encounters an exitif statement with a true value, it
terminates the loop processing and continues scanning the
tokens after the loop.

MP does not expand the loop fully and then evaluate, but
rather does what it can when it can, expanding further only
when it needs more tokens.

>  Where can this
>be explained in the Metapost documentation ?

The Metapost language and syntax is almost identical to
Metafont's. The only complete explanation in
"The METAFONTbook" by D.E. Knuth.

Dan

Daniel H. Luecking
Department of Mathematical Sciences
University of Arkansas
"Dubito ergo cogito, cogito ergo sum" --Descarte

```