How can I check if a symbol is pre-defined by Mathematica, in a way that's backwards compatible with old versions?
i.e. I would like some CoreLanguageQ[x_Symbol]
which matches CoreLangaugeQ[Print]
, but not CoreLanguageQ[f]
Then it can be used to help make code backwards compatible, eg.
If[!CoreLanguageQ[Echo], Echo[x_]:= (Print[x];x)]
Thank you.
Answer
You can look it up using WolframLanguageData
, which has a list of all pre-defined symbols:
ClearAll[CoreLanguageQ]
SetAttributes[CoreLanguageQ, HoldAll]
CoreLanguageQ[x_] := With[{name = SymbolName[x]}, CoreLanguageQ[name]]
CoreLanguageQ[x_String] := With[{
names = WolframLanguageData[All, "Name"]
}, MemberQ[names, x]]
CoreLanguageQ[Plot]
(* Out: True *)
CoreLanguageQ[Plott]
(* Out: False *)
Looking at the context of the symbol is also a viable approach. However, the WolframLanguageData
approach is appealing because the documentation states that
WolframLanguageData[] gives a list of all Wolfram Language symbols.
Which is to say, the list returned by this function is by definition Wolfram Language. This is as close as a definition of "core language" that we can come.
For the problem in the updated question, it would seem appropriate to check if a symbol exists in the System
context like QuantumDot suggests in a comment.
The only backward compatible way to use this would be to create lists of functions available for specific versions and include them in your code. For example:
names = WolframLanguageData[All, "Name"];
versionIntroduced = WolframLanguageData[All, "VersionIntroduced"];
allowed = Pick[names, Thread[versionIntroduced <= 10]];
In this code, allowed
holds all the symbols that exist in version 10, presuming that no symbol previously introduced was removed.
Comments
Post a Comment