Equivalent to 'defined' in Mathematica

I need a function that takes the name of a character as a string and whether that character returns is already defined. The function ValueQis close, but returns False for function names. In addition, it accepts characters, not 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 test both DownValues ​​and SubValues.

+3
source share
3 answers

I put this together, which seems to work:

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

I hope there will be a more beautiful solution.

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

+2
source

I think names should do the trick:

The names ["string"] list the names of characters that match the string.

Names [ "foo" ] {}, foo , { "foo" }. , "" :

defined[str_] := Names[str] != {}

, , "7", 7 . , , NumberQ.

, Symbol, ( ) , .

[ "name" ] .

[] .

EDIT. , , , NameQ [ "name" ] , . , , , .

+2

DownValues, , "", . ,

f[x_, y_] := x + y

g[3] = 72 * a;

,

h[a_][b] = "gribble";

. , ( , Hold, !). , DownValues, SubValues:

functionNameQ[name_String] := 
    With[{ hSymbol = ToExpression[name, InputForm, Hold] },
        MatchQ[hSymbol, Hold[_Symbol]] &&
            ((DownValues @@ hName) =!= {} || (SubValues @@ hName) =!= {})];
+2

Source: https://habr.com/ru/post/1718063/


All Articles