picking specific symbol definitions in mathematica (not transformation rules)

后端 未结 3 1839
说谎
说谎 2021-01-12 19:28

I have a following problem.

f[1]=1;
f[2]=2;
f[_]:=0;

dvs = DownValues[f];

this gives

dvs = 
   {
      HoldPattern[f[1]] :         


        
3条回答
  •  攒了一身酷
    2021-01-12 19:41

    Leonid, of course, completely answered the question about why your temporary solution works but HoldPattern does not. However, as an answer to your original problem of extracting the f[1] and f[2] type terms, his code is a bit ugly. To solve just the problem of extracting these terms, I would just concentrate on the structure of the left-hand-side of the definition and use the fact that FreeQ searches at all levels. So, defining

    f[1] = 1;  f[2] = 2;  f[_] := 0;
    dvs = DownValues[f];
    

    All of the following

    Select[dvs, FreeQ[#, Verbatim[_]] &]
    Select[dvs, FreeQ[#, Verbatim[f[_]]] &]
    Select[dvs, ! FreeQ[#, HoldPattern[f[_Integer]]] &]
    

    yield the result

    {HoldPattern[f[1]] :> 1, HoldPattern[f[2]] :> 2}
    

    Provided there are no f[...] (or, for the first version, Blank[]) terms on the right-hand-side of the downvalues of f, then one of the above will probably be suitable.

提交回复
热议问题