# [metapost] Function defined by a sum

Nicolas FRANCOIS nicolas.francois at free.fr
Fri Nov 2 14:33:09 CET 2007

```Le Fri, 2 Nov 2007 13:16:26 +0100 "Mojca Miklavec"
<mojca.miklavec.lists at gmail.com> a écrit :

> On 11/2/07, Nicolas FRANCOIS wrote:
> > Le Fri, 2 Nov 2007 11:21:19 +0100 "Mojca Miklavec"
> > <mojca.miklavec.lists at gmail.com> a écrit :
> >
> > 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;

Well, except it is "    + sin(k*x)/k"

> Sure, that's a more elegant solution. It gets expanded directly into
>     return 0+sin(1*x)/1+sin(2*x)/2+...+sin(n*x)/n (whatever n is)
> while my example was doing
>     sum:=0;
>     sum:=sum+sin(1*x)/1;
>     sum:=sum+sin(2*x)/2;
>     ...
>     return sum
>
> > I thought something like this could work. But I don't know exactly why.
> > Is this something like "token replacement", like in TeX ? Where can this
> > be explained in the Metapost documentation ?
>
> It's described a bit in "Loops" (section 10, page 85 in the manual for
> version 1.000).
>
> It's exactly the same trick that is used afterwards for drawing the
> path. I don't know how to explain it (for is like a macro that appends
> the content to what we had before the loop instead of executing some
> commands step-by-step - the content is then "evaluated" when the first
> ";" appears - sorry for the horrible wording, but I really have no
> idea how to explain it in any other way. Read the section 1 of mpman
> carefully).

Thanks, Mojca. I still have much to learn from Metapost. This language is
definitly great, but hard to begin with.

More will you learn from looking at more examples, and back to the doc
you will go then to understand more profundly the power of Metapost (would
say Master Yoda ;-)

\bye

--

Nicolas FRANCOIS
http://nicolas.francois.free.fr
A TRUE Klingon programmer does NOT comment his code
```