Function Repository Resource:

ExtractDownValues

Source Notebook

Extract all DownValues that match the input

Contributed by: Carl Woll

ResourceFunction["ExtractDownValues"][expr]

finds all DownValues that match expr, in the order in which they would be applied by the pattern matcher.

ResourceFunction["ExtractDownValues"][head,args]

finds all DownValues of head that match head[args].

Details and Options

Unless one of the DownValues uses Condition, the first DownValues should be the one that is used by the pattern matcher.

Examples

Basic Examples (3) 

Define a function:

In[1]:=
abs[c_Complex] := Sqrt[Re[c]^2 + Im[c]^2]
abs[n_Real] := Sign[n] n
abs[n_?NumericQ] /; MemberQ[{-1, 0, 1}, Sign[n]] := Sign[n] n
abs[x_] := x

Find the DownValues that match abs[23.1]:

In[2]:=
ResourceFunction["ExtractDownValues"] @ abs[23.1]
Out[2]=

Use the two-argument version to find the DownValues that match abs[c] where c=2+I:

In[3]:=
c = 2 + I;
ResourceFunction["ExtractDownValues"][abs, Evaluate @ c]
Out[3]=

Applications (6) 

Find a spoken string:

In[4]:=
SpokenString[HoldForm[x + y /. x -> 2]]
Out[4]=

Suppose you want to use "where" instead of "slash dot" in this spoken string. Use TracePrint to find the arguments to the internal function SpokenStringDump`SSText used to form the spoken string:

In[5]:=
TracePrint[SpokenString[HoldForm[x + y /. x -> 2]], SpokenStringDump`SSText[_ReplaceAll]]
Out[5]=

The internal function used by SpokenString has many DownValues:

In[6]:=
Length @ DownValues @ SpokenStringDump`SSText
Out[6]=

ExtractDownValues can find the first downvalue that matches:

In[7]:=
First @ ResourceFunction["ExtractDownValues"] @ SpokenStringDump`SSText[x + y /. x -> 2]
Out[7]=

Modify this downvalue:

In[8]:=
SpokenStringDump`SSText[a_ /. b_] := SpokenStringDump`SpeakQuantity[a, ReplaceAll, True] ~~ " where " ~~ If[ListQ[Unevaluated[b]], SpokenStringDump`SpeakListContents[b], SpokenStringDump`SpeakQuantity[b, ReplaceAll, True]]

Check the new output:

In[9]:=
SpokenString[HoldForm[x + y /. x -> 2]]
Out[9]=

Properties and Relations (2) 

When matching patterns, evaluation leaks can occur. Here is a function that has a side effect:

In[10]:=
foo[x_] /; (Print[x]; False) := 1

Using ExtractDownValues causes the condition to be evaluated:

In[11]:=
ResourceFunction["ExtractDownValues"] @ foo[3]
Out[11]=

Publisher

Carl Woll

Version History

  • 1.0.0 – 22 October 2019

Related Resources

License Information