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
Here's a nice, simple solution which works if the object in question has enough internal structure.
You can use
to detect whether
variable
has been assigned to something with more than one part. Thus:You can then use
Length[variable]>0
to getTrue
in the latter case.This fails, though, if there's a chance that
variable
be assigned to an atomic value, such as a single string or number:What's the intended use?
If I understood correctly I think the function
ValueQ
is what you are looking for. It will return true if a variable or a function has been defined and false if it has not been defined.Read more at http://reference.wolfram.com/mathematica/ref/ValueQ.html
Actually, the ValueQ function is not innocent, since it leaks evaluation for code with side effects. Examples:
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):
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.