[metapost] how to get the size of an array
Dan Luecking
luecking at uark.edu
Wed Aug 1 21:32:21 CEST 2007
At 09:25 AM 8/1/2007, you wrote:
>Hello,
>I have two questions:
>
>1) suppose I have an array defined like that
>
>numeric range[];
>
>rang[1]:=3; ...
>
>how can I now the size of this array ?
If you are the programmer defining the array, you can
enforce certain conventions. In the MF/MP support for
the mfpic package we use the following. The name "list"
should be more evocative, maybe "list_to_array", but
it was the name I inherited when I took over the
maintenance:
def list (suffix name)(text lst) =
name := 0;
for _itm = lst:
name[incr name] := _itm;
endfor
enddef;
def setarray (text kind) (suffix name) =
save name; kind name[]; list (name)
enddef;
When used like
setarray (pair)(X)((1,2),(3,1),origin)
we get a numeric variable X whose value is 3;
and three pair variables X1, X2 and X3 whose values
are (1,2), (3,1) and (0,0), resp.
With this setup, the length of the array with basename
"X" is the value of X.
The above makes the definitions local if inside
begingroup...endgroup, but one could make it global:
replace "save name" with "numeric name". MFpic has a
gsetarray macro that does this. Using "save name" means
the array name cannot have a suffix. This has occasionally
been a problem, but not often.
With this setup, the length of the array with basename
"X" is the value of X.
A possibly better (but more verbose) approach is to
change the definition so that X.len is the length and
perhaps add a definition of a string X.type (equal to
the "pair" in this example). One can then test whether
X is an array by testing if X.len is a known numeric and
get the type by examining X.type. To be even more careful,
we could add a boolean X.isarray and perhaps even other
information (e.g., a boolean X.global).
If one is careful to always use specialized macros to set up and
modify arrays, one is ensured that the information is correct.
Dan
Daniel H. Luecking
Department of Mathematical Sciences
University of Arkansas
"Dubito ergo cogito, cogito ergo sum" --Descarte
More information about the metapost
mailing list