16
$\begingroup$

I'm doing some metaprogramming. How would I make a Mathematica function that returns a random Mathematica command? Is there a list of command names that I could use RandomChoice on?

I'm looking for something better than selecting random letters until getting Protected in the Attributes, which is all I've been able to think of so far.

$\endgroup$
22
$\begingroup$

There are a lot of commands! One way to get a list is to use Names["*"], which will return all the symbols Mathematica knows. Since commands start with capital letters, you can gain more control over the list by asking for only a subset. For example,

all = {"A*", "B*", "C*"};
Names[#] & /@ all

provides a list of all commands that start with A, B, or C. You could customize the all to suit your preferences.

$\endgroup$
  • 1
    $\begingroup$ Nowadays, one can use WolframLanguageData["RandomEntities"]. $\endgroup$ – J. M. will be back soon Jun 7 '16 at 10:01
12
$\begingroup$

Get the full list of Mathematica functions here:

myFunctionList = Import["http://reference.wolfram.com/language/guide/\
AlphabeticalListing.html"];

Strip the list of header and footer material, and select a random element:

RandomChoice[StringSplit[StringTake[myFunctionList, {3245, -1225}]]]

Or, based on the approach of bill s:

RandomChoice@Flatten[Names[#] & /@ (StringJoin[#, "*"] & /@ CharacterRange["A", "Z"])]
$\endgroup$
10
$\begingroup$

Here's a piece of code that lets you see random Wolfram Language code snippets, rather than just command names.

RandomExample[] := Module[{dir, file, inputs, output, cap, i = 0, j = 1, in},
    dir = DirectoryName[FindFile["ExamplePages/CreateMolecularGraphs.nb"]];
    file = RandomChoice[FileNames["*", dir]];
    output = Import[file, {"Cells", "Output"}][[1]];

    cap = CellLabel /. Options[output];
    If[!StringQ[cap], Return[$Failed]];
    cap = ToExpression[StringReplace[cap, "Out[" ~~ x__ ~~ "]" ~~ __ :> x]];

    inputs = Import[file, {"Cells", "Input"}];

    CellPrint[TextCell[
        StringReplace[file, __ ~~ "ExamplePages" :> "ExamplePages"],
        "Subsubsection"
    ]];

    CellPrint[Reap[
        While[i < cap && j <= Length[inputs],
            in = CellLabel /. Options[inputs[[j]]];
            If[StringQ[in],
                i = ToExpression[StringReplace[in, "In[" ~~ x__ ~~ "]" ~~ __ :> x]]
            ];
            Sow[inputs[[j++]]]
        ]
    ][[-1, 1]]];

    CellPrint[output];
]

enter image description here enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.