Re: associative arrays
- To: mathgroup at smc.vnet.net
- Subject: [mg63885] Re: associative arrays
- From: albert <awnl at arcor.de>
- Date: Fri, 20 Jan 2006 04:32:46 -0500 (EST)
- References: <dqn7t9$l8m$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
ekantian wrote:
> ok, i know from this group that to see keys in a hash (as in per keys
> %hash) in would use
hm. You should be aware that there is a big difference between using
mathematica downvalues and perl-hashes, even though for simple use cases
they look very similar...
> keys[hash_] := Map[#[[1, 1, 1]] &, DownValues[hash]];
>
> however, what if i have multiple levels of keys, like
>
> a[levelone][leveltwo]={1,2,3}
> a[levelone][level2]={4,5,6}
> a[levelA][levelB]={7,8,9}
>
> I need keys[a] to give me {levelone, levelA} and keys[a[levelone]] to
> give me {leveltwo, level2}, etc.
Look at SubValues[a]. From this you can construct something that works as
you want along the lines of the DownValues-Trick.
Probably it would be a better idea to construct something more hierachical,
depending on what you want to achive, e.g.:
a[levelone]=dummy1
dummy1[leveltwo]={1,2,3}
You could write code that constructs something like that and use Unique to
automatically generate dummy-symbols using something like (of course you
might want to make this work with arbitrary depth and add checks to whether
there are entries already...):
WriteToNestedHash[a,{l1_,l2_},val_]:=With[{dummy=Unique[$dummy]},
a[l1]=dummy;
dummy[l2]=val;
]
Anyway, be warned that it might not be a very good idea to try to write
Mathematica code as a literal translation of perl code...
hth
albert