[metapost] (newbie) macro with a sequence of pairs

Boguslaw Jackowski B_Jackowski at GUST.org.pl
Tue Dec 15 10:42:32 CET 2009


Hello,

Luigi Scarso:
> I'm pretty new about metapost programming
> and I need to write a "polyline" macro
> that take a with a "sequence of pairs"  like
> (0,0) (10,10) (30,10)
> and draw  a line
> ie
> polyline (0,0) (10,10) (30,10)
> is
> draw (0,0)--(10,10)--(30,30)
> 
>  Is it possible ?

Taco Hoekwater:
> Not without a lot of trickery, I think. Why do you
> not want to use
>   polyline (0,0)--(10,10)--(30,30);

I could fancy a situation when I would prefer to manipulate with bare
list of components (pairs) rather than with a resulting object (path).

The problem is that MP "likes" very much separators. So, I'd suggest
devising a macro invoked, e.g., in such a manner:

   polyline (0,0), (10,10), (30,10);

(Of course, a path can be splitted to nodes, but such a solution seems not
sufficiently elegant to me ;-)

Actually, the solution to Luigi's problem would be to convert first
a series of pairs into a comma-separated list:

%%%% BEGIN OF LUIGIS.mp

def sentinel = (infinity,infinity) enddef;

def convert_items_to_list expr e =
  if e=sentinel: sentinel else: e , convert_items_to_list fi
enddef;

vardef convert_items_to_path(text items) =
  hide(path_started:=whatever)
  for i=convert_items_to_list items sentinel:
   if i<>sentinel:
    if known path_started: -- else: hide(path_started:=1) fi i
   fi
  endfor
enddef;

beginfig(100)
  draw convert_items_to_path (
   (0,1) (2,2) (3,1) ((4,1)+(2,2))
  ) scaled 100;
endfig;

end.

%%%% END OF LUIGIS.mp

Note that the whole input series of items needs also to be separated -- 
either with a semicolon, or with parentheses; I used the latter form.

The trick with the `sentinel' constant ensures that recursively invoked
convert_items_to_list will not be fed with an empty argument.

The trick with the `path_started' variable appears fairly frequently
in (my ;-) MP programs.

Cheers -- Jacko

-- 
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  Bogus\l{}aw Jackowski: B_Jackowski at GUST.ORG.PL
----------------------------------------------------------------
  Hofstadter's Law: It always takes longer than you expect, even
                    when you take into account Hofstadter's Law.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-




More information about the metapost mailing list