Re: Returning a local array

*To*: mathgroup at smc.vnet.net*Subject*: [mg84196] Re: Returning a local array*From*: Albert Retey <awnl at arcor.net>*Date*: Thu, 13 Dec 2007 05:50:04 -0500 (EST)*References*: <fjqj9l$6l9$1@smc.vnet.net>

Hi, > I would like to return a local array. The below seems like the wrong > way to do it: > > f[] := Module[{h}, h["a"] = 1; h["b"] = 2; h]; > g = f[]; > > I would like g not to be associated with the local variable h, but > equivalent to defining it as follows: > > g["a"] = 1; g["b"] = 2; What is wrong with this approach? While the actual rules are defined as Downvalues for h (or, since it is local something like h$456) setting g to this h makes things like: g["a"] work as (probably) expected. What is your specific problem with this approach? The only thing you would probably need is an explicit delete to remove the local symbol when not needed anymore, but this is only necessary if you really need to avoid "memory leaks"... Another thing you could do is to supply the symbol as an argument like: f[v_]:=(v["a"]=1;v["b"]=2;v) and then use: f[g] If you don't like the syntax, you can make that approach look like the other by using UpValues: f/:(v_=f[]):=(v["a"]=1;v["b"]=2;v) > Is it better to work with rules instead? It can become awkward and I > would like to avoid it. > > f[] := Module[{h}, h={"a" -> 1, "b" -> 2}; h]; > g = f[]; > "a" /. g This is probably a way which is more often seen in Mathematica code. Anyway there are counterexamples and your above strategy for "misusing" the pattern matcher to construct data structures is used elsewhere, too, and I think I have seen it used even within parts of Mathematica's own standard libraries... Note that you could also define a supporting function which makes the access look more familiar: get[rules_,attr_]:=attr/.rules; get[g,"a"] > The specific problem is I am reading the header for a binary file that > has 20 or so parameters describing the binary file. I thought this > would be the analog of a structure in other languages and a good way > to put these parameters in a variable. actually I think of this as a lookup table, dictionary, hashtable or whatever it is called in other languages and use constructs like that all the time. hth, albert