1
$\begingroup$

Suppose I have a symbol/function defined pointwise like in

f[1, 5] = 3
f[3] = 7
f[2, 3.4] = 8

By executing ?f I can see the definition of f, i.e.

Global`f
f[3]=7
f[1,5]=3
f[2,3.4]=8

How can I get a list of all parameter tuples for which the function is defined? In my example I would like to obtain the list

{{1,5},{3},{2,3.4}}

Is that possible?

$\endgroup$

1 Answer 1

1
$\begingroup$

You can use DownValues[f] to get the list of rules, the structure of which uses HoldPattern to prevent the evaluation.

DownValues[f]
{HoldPattern[f[3]] :> 7, HoldPattern[f[1, 5]] :> 3, HoldPattern[f[2, 3.4]] :> 8}

If you replace f with List and extract the correct part of the expressions that should return what you are after:

(DownValues[f] /. f -> List)[[All, 1, 1, All]]
{{3}, {1, 5}, {2, 3.4}}

Note that the list has been sorted (in how DownValues reports the structure).

$\endgroup$
6
  • $\begingroup$ I'd use Cases[DownValues[f], HoldPattern[f[val__]] :> {val}, ∞] myself. $\endgroup$ Commented Jun 3, 2015 at 9:52
  • $\begingroup$ Great! Exactly what I need. I wasn't aware of DownValues[]. $\endgroup$
    – cgogolin
    Commented Jun 3, 2015 at 9:53
  • $\begingroup$ @Guesswhoitis, I was sure that someone would produce a smarter looking version! And that looks a lot neater than having to work out which levels to take the Part of, which is what I generally end up doing. $\endgroup$
    – SPPearce
    Commented Jun 3, 2015 at 10:01
  • 1
    $\begingroup$ @cgogolin, there are UpValues, DownValues, SubValues and OwnValues, all of which let you get at various types of definitions. $\endgroup$
    – SPPearce
    Commented Jun 3, 2015 at 10:01
  • $\begingroup$ Why do you put the last All in [[All, 1, 1, All]]? For any list f it is true that f[[All]] === f, after all. $\endgroup$
    – Jo Mo
    Commented Aug 19, 2021 at 8:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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