Does anybody know if there is a built-in function in Mathematica for getting the lhs of downvalue rules (without any holding)? I know how to write the code to do it, but it seems basic enough for a built-in
For example:
a[1]=2;
a[2]=3;
BuiltInIDoNotKnowOf[a]
returns {1,2}
This seems to work; not sure how useful it is, though:
This is like
keys()
in Perl and Python and other languages that have built in support for hashes (aka dictionaries). As your example illustrates, Mathematica supports hashes without any special syntax. Just saya[1] = 2
and you have a hash. [1] To get the keys of a hash, I recommend adding this to your init.m or your personal utilities library:(Or the following pure function version is supposedly slightly faster:
)
Either way,
keys[a]
now returns what you want. (You can get the values of the hash witha /@ keys[a]
.) If you want to allow for higher arity hashes, likea[1,2]=5; a[3,4]=6
then you can use this:Which returns
{{1,2}, {3,4}}
. (In that case you can get the hash values witha @@@ keys[a]
.)Note that
DownValues
by default sorts the keys, which is probably not a good idea since at best it takes extra time. If you want the keys sorted you can just doSort@keys[f]
. So I would actually recommend this version:Interestingly, there is no mention of the
Sort
option in theDownValues
documention. I found out about it from an old post from Daniel Lichtblau of Wolfram Research. (I confirmed that it still works in the current version (7.0) of Mathematica.)Footnotes:
[1] What's really handy is that you can mix and match that with function definitions. Like:
You can then add memoization by changing that last line to
which says to cache the answer for all subsequent calls.