Yes I know there is no built-in native function called SymbolQ
(but JavaScript does). However, could one be simulated to work for most cases? I often rely on objectName[symbol]
and makeRuleRow[symbol]
to return the name of a defined variable and its value in a ready-to-use row for structured Grid
layouts of results to computations. However, sometimes an error is returned if a variable is not a Symbol
which leaves me asking, "When is a symbol a Symbol
?"
I would like to catch such errors and return as much useful information as possible. That is why I ask if there is an easy hack for determining if a variable is a symbol.
Here is some working code where I might use such a function...
SetAttributes[symbolQ, HoldAllComplete];
symbolQ[x_] := ResourceFunction["SymbolQ"][x];
SetAttributes[{objectName}, HoldFirst];
objectName = Function[Null, SymbolName[Unevaluated[#]], {HoldFirst}];
objectName::usage =
"objectName@# returns Unevaluated shortened SymbolName.";
SetAttributes[{makeRuleRow}, HoldFirst];
makeRuleRow[symbol_, altname_ : Null, desc_ : Null] :=
Module[{name = "", prepend = ""},
If[ResourceFunction["SymbolQ"][symbol] === False &&
altname === Null,
Return[Row[{Style["Argument ", Red], symbol,
Style[" is not a symbol. Use altname in makeRuleRow.", Red]}]
], False
];
name = If[StringQ[altname], altname, objectName[symbol]];
prepend = If[StringQ[desc], desc <> " ", ""];
{Row[{Style[prepend, Brown], name, rule}],
TraditionalForm[symbol]}
]
The following is how it would be used for most cases (including an error) expected to be encountered when setting up name-value pairs for Grid
row elements...
xxx = 123;
makeRuleRow[xxx] (* this outputs name and value *)
makeRuleRow[xxx, "alternate name"] (* this creates alternate name *)
makeRuleRow[xxx, "alternate name", "this is a symbol"] (* this prepends a description and creates alternate name *)
makeRuleRow[69] (* this generates an error message suggesting a fix *)
makeRuleRow[69, "XXX"] (* bypasses error by creating alternate name *)
makeRuleRow[69, "XXX", "not a symbol"] (* bypasses error by creating alternate name and prepend a description *)
The actual output when done correctly conveniently makes {name ->, value}
rows ready to be inserted into two-column Grid layouts...
{xxx -> ,123}
{alternate name -> ,123}
{this is a symbol alternate name -> ,123}
Argument 69 is not a symbol. Use altname in makeRuleRow.
{XXX -> ,69}
{not a symbol XXX -> ,69}
SymbolName
works? Something like:symbolQ[x_]:=Quiet[Check[StringQ@SymbolName[x], False, General::sym], General::sym]
$\endgroup$ResourceFunction["SymbolQ"][x]
to the clipboard. The function will download automatically. You can also download the source notebook if you want to see how it works internally. $\endgroup$symbolQ = ResourceFunction["SymbolQ"]
. My kernel init.m file is filled with definitions like that. $\endgroup$