Search code examples
wolfram-mathematicautilities

Equivalent of "defined" in Mathematica


I need a function that takes the name of a symbol as a string and returns whether that symbol is already defined. The function ValueQ is close but it returns False for function names. Also, it takes symbols rather than strings.

Examples:

defined["N"] --> True (predefined function N)
defined["x"] --> False
x = 7;
defined["x"] --> True (x is now defined)
defined["7"] --> True (7 is a number)
f[x_] := 2x
defined["f"] --> True (f has DownValues)
g[x_][y_] := x+y
defined["g"] --> True (g has SubValues)

PS: Thanks to Pillsy for pointing out the need to check for both DownValues and SubValues.


Solution

  • I cobbled this together, which seems to work:

    defined[s_] := ToExpression["ValueQ[" <> s <> "]"] || 
                   Head@ToExpression[s] =!= Symbol || 
                   ToExpression["Attributes[" <> s <> "]"] =!= {} ||
                   ToExpression["DownValues[" <> s <> "]"] =!= {} ||
                   ToExpression["SubValues[" <> s <> "]"] =!= {}
    

    Hopefully there's a prettier solution.

    PS: Thanks to Pillsy for pointing out the need to check for both DownValues and SubValues.