3
$\begingroup$

This should have a simple solution, but for some reason I cannot find how to do this.

Let's say I have a "function" where I have defined values (in my actual example I have many instances of this, but here I will just show 3).

func[1] = 3;
func[2] = 5;
func[3] = 9;

I can see what all of the definitions of func are by just calling

Definition[func]

func[1] = 3

func[2] = 5

func[3] = 9

But what if I want to explicitly access all of the definitions I have made for func. In other words, how can I just get a list of the "inputs" that have been defined? Something like:

{1, 2, 3}

$\endgroup$
6
  • $\begingroup$ Maybe (DownValues[func] /. func -> List)[[All, 1, 1]] does what you want? $\endgroup$ Nov 5 '19 at 19:20
  • 3
    $\begingroup$ I would use DownValues[func][[All, 1, 1, 1]]. $\endgroup$
    – Carl Woll
    Nov 5 '19 at 19:30
  • $\begingroup$ @CarlWoll Think about multiple-argument definitions like func[3, 5] = 19;... $\endgroup$ Nov 5 '19 at 20:21
  • 1
    $\begingroup$ Maybe ReplacePart[DownValues[func], {_, 1, 1, 0} -> List][[All, 1, 1]] is a bit more robust. Just in case func appears as its own argument like in func[func] = 0 ... $\endgroup$ Nov 5 '19 at 20:25
  • $\begingroup$ @CarlWoll That works fine :) I knew it was a simple fix. I had completely forgot about DownValues. Thank you! $\endgroup$ Nov 5 '19 at 21:49
4
$\begingroup$
func[1] = 3;
func[2, 3] = 5;
func[3, 4, 5] = 9;

To get a list of all the inputs and outputs of a function you can use DownValues.

DownValues@func

{HoldPattern[func[1]] :> 3, HoldPattern[func[2, 3]] :> 5, HoldPattern[func[3, 4, 5]] :> 9}

Then to get all the inputs associated with explicit definitions, first replace the func head with List (in case of multiples arguments) and you then can use Keys

(Keys@DownValues@func /. func -> List)[[;; , 1]]

{{1}, {2, 3}, {3, 4, 5}}

or manually pick out the part

(DownValues@func /. func -> List)[[;; , 1, 1]]

{{1}, {2, 3}, {3, 4, 5}}

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