5
$\begingroup$

Assume that definitions like the following are in place:

f[alpha] = "artichoke";
f[bravo] = "beet";
f[charlie] = "celery";
...
f[yankee] = "yam";
f[zulu] = "zucchini";

etc. (Also assume that all the symbols alpha, bravo, charlie, ..., yankee, zulu evaluate to themselves.)

I'm looking for a way to get a list of all the symbols for which f is defined. IOW, given f, I'm looking for a way to get the list of symbols

{alpha, bravo, charlie, ..., yankee, zulu}

(Note that, for the query I'm interested in here, the values associated with the definitions are irrelevant.)

The closest I've found is to somehow scrape the output of Information[f] (or Definition[f]), which strikes me as a horrible prospect.

Is there a more civilized approach?

$\endgroup$
  • 3
    $\begingroup$ Try First[#][[1, 1]] & /@ DownValues[f]. $\endgroup$ – Virgil May 1 '15 at 5:08
  • $\begingroup$ Equivalent to Level[DownValues[f], {4}]. $\endgroup$ – Virgil May 1 '15 at 5:19
  • $\begingroup$ @Virgil. Nice, but not always equivalent. Try f[alpha]={{beta}}. Then Level[DownValues[f], {4}] returns {alpha, beta}. $\endgroup$ – Fred Simons May 1 '15 at 6:49
  • 3
    $\begingroup$ @Virgil This DownValues[f][[All, 1, 1, 1]] will behave slightly faster for large DownValues. $\endgroup$ – Rolf Mertig May 1 '15 at 7:09
  • $\begingroup$ @FredSimons: good point. $\endgroup$ – Virgil May 1 '15 at 12:50
4
$\begingroup$

Barbarism can be avoided through judicious application of DownValues. Using RolfMertig's suggestion, you can get what you want with

f[alpha] = "artichoke";
f[bravo] = "beet";
f[charlie] = "celery";
...
f[yankee] = "yam";
f[zulu] = "zucchini";

DownValues[f][[All, 1, 1, 1]]

(* -> {alpha, bravo, charlie, ..., yankee, zulu} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.