MathGroup Archive 2007

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Returning a local array

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


> 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:


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:


and then use:


If you don't like the syntax, you can make that approach look like the 
other by using UpValues:


> 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:



> 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.



  • Prev by Date: Re: Returning a local array
  • Next by Date: Re: Arrows on curves
  • Previous by thread: Re: Returning a local array
  • Next by thread: Re: Returning a local array