MathGroup Archive 1998

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

Search the Archive

Re: keys in a hash table (aka, all assigned indices in an array): awful hack

  • To: mathgroup at smc.vnet.net
  • Subject: [mg13347] Re: [mg13281] keys in a hash table (aka, all assigned indices in an array): awful hack
  • From: Carl Woll <carlw at fermi.phys.washington.edu>
  • Date: Mon, 20 Jul 1998 02:50:02 -0400
  • Sender: owner-wri-mathgroup at wolfram.com

Hi Daniel,

I see a couple of problems with your approach. First, the keys may also
have downvalues. Suppose that you have the definitions

apple = MacIntosh

fruits[apple] = crunchy
fruits[lemon] = sour

Then your keys function would return {MacIntosh,lemon} instead of
{apple,lemon}. This is why DownValues uses HoldPattern in its answer.
So, you might want to modify your function to return 

Hold[MacIntosh, lemon] or

something similar. However, this isn't sufficient, since we also have
problem number 2. That is, what if your function has multiple
arguments? It might not make sense for your example, but suppose you
also have a definition like

fruits[lemon, citrus] = True

Then your function keys would miss out on this second argument. So you
probably want the answer to look something like

Hold[{apple},{lemon,citrus}]

The following function will return the above:

ClearAll[Domain,ReplaceHead]
Domain[s_] := 
        Distribute[
                        Apply[ReplaceHead,First/@DownValues[s],1],
                        Hold, List, Hold, Sequence
                  ]

SetAttributes[ReplaceHead, {HoldAll}] ReplaceHead[h_[args___]] :=
Hold[{args}]

Of course, First/@DownValues[s] is very similar to what the above
function returns and is probably good enough.

Carl Woll
Dept of Physics
U of Washington

On Fri, 17 Jul 1998, Daniel Reeves wrote:

> suppose I make some assignments like this:
>   fruits[apple]= crunchy
>   fruits[lemon]= sour
> 
> I'm treating fruits like a hash table and now I would like a list of all
> the keys.  In this case {apple,lemon}.
> 
> It seems like there should be an easy way to do this. All I came up with
> was the following hack:
> 
> keys[hash_]:= 
>   DownValues[hash] /. {RuleDelayed->(#&), hash->(#&)} //ReleaseHold
> 
> 
> the hash values will be simple; we can just do fruits/@keys[fruits]
> 
> Thanks,
> Daniel
> 
> --
> Daniel Reeves  dreeves at umich.edu  http://interlabs.bradley.edu/~daniel
> 
> "Computer Science is no more about computers than astronomy is about
> telescopes."  -- E W Dijkstra
> 
> 



  • Prev by Date: Help on (* comments *)
  • Next by Date: output to a plain text file
  • Previous by thread: Re: keys in a hash table (aka, all assigned indices in an array): awful hack
  • Next by thread: Is UNDO that limited in Mathematica3.0/Win95?