Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

wolfram mathematica - Checking if a symbol is defined

Is there an easy way to check if there's a definition for x? I need a function that takes something of the form f,f[_] or f[_][_] and returns True if there's a definition for it

To be really concrete, I'm storing things using constructs like f[x]=b, and g[x][y]=z and I need to check if f[x] has definition for every x in some list and if g[x][y] has a definition for every x,y in some set of values

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Actually, the ValueQ function is not innocent, since it leaks evaluation for code with side effects. Examples:

ClearAll[f, g]; 
f[x_] := Print[x]; 
g[x_][0] := Print[x];
{ValueQ[f[1]],ValueQ[g[2][0]]}

If you remove the ReadProtected Attribute of ValueQ and look at the code, you will see why - the code is very simplistic and does a decent job for OwnValues only. Here is a more complex version which I developed to avoid this problem (you can test that, at least for the examples above, it does not leak evaluation):

ClearAll[symbolicHead];
SetAttributes[symbolicHead, HoldAllComplete];
symbolicHead[f_Symbol[___]] := f;
symbolicHead[f_[___]] := symbolicHead[f];
symbolicHead[f_] := Head[Unevaluated[f]];

ClearAll[partialEval];
SetAttributes[partialEval, HoldAllComplete];
partialEval[a_Symbol] /; OwnValues[a] =!= {} := 
   Unevaluated[partialEval[a]] /. OwnValues[a];

partialEval[a : f_Symbol[___]] /; DownValues[f] =!= {} :=
   With[{dv = DownValues[f]},
      With[{eval = Hold[partialEval[a]] /. dv},
         ReleaseHold[eval] /; 
           (First[Extract[eval, {{1, 1}}, HoldComplete]] =!= 
           HoldComplete[a])]];

partialEval[a_] :=
   With[{sub = SubValues[Evaluate[symbolicHead[a]]]},
      With[{eval = Hold[partialEval[a]] /. sub},
         ReleaseHold[eval] /; 
           (First[Extract[eval, {{1, 1}}, HoldComplete]] =!= 
           HoldComplete[a])]];

ClearAll[valueQ];
SetAttributes[valueQ, HoldAllComplete];
valueQ[expr_] := partialEval[expr] =!= Unevaluated[partialEval[expr]];

This is not complete either, since it does not account for UpValues, NValues, and FormatValues, but this seems to be enough for your stated needs, and also, rules for these three extra cases can perhaps also be added along the same lines as above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...