# A \newcommand type option that runs all subarguments and saves static text

I am trying to write code that uses sage in it, and have a bit of a problem with randomizing stuff around the code. The sagetex part isn't too important (I don't think), what is important is that if I use a

\newcommand{\foo}{(SAGETEXHERE)}


then whenever I run the command \foo it reruns the sage text... which is a problem.

Here is an example of the current pseudo-code

\begin{sagesilent}
func1 = x - 3
func2 = x + 1
f = expand(func1*func2)
\end{sagesilent}

\newcommand{\foo}{\sage{f}}


Here, what would normally happen is sage silent runs sage, and creates the correct f = x^2 - 2x - 3. Then every time \foo is called, it reruns an instance of sage to go locate the definition of f in the sage file, and then sage will spit out the definition in text to \foo which then will display f. This is taking a lot of compute time unnecessarily, and when things get randomized it all goes to hell.

Is there any way to force a command to take in the definition when it's defined, and then save that definition as straight up text so that I don't have to rerun sage to go find the definition of f every time I want to call \foo?

EDIT: I have come up with a non sage version that should be equivalent.

Using the lgc package, here's my MWE:

\usepackage[first=1]{lcg}
\newcommand{\Temp}{\genrand{A}{1}{10} \arabic{A}}
\begin{document}
\Temp
\Temp
\Temp
\end{document}


In this example the \Temp would give 3 different numbers, but what I am after is some way to build a second macro, maybe \Temp2 so that it expands \Temp when \Temp2 is defined, and then every time \Temp2 runs it gives the same number. Notice this is by way of example, in this particular case I could save the first random number in a counter and then keep calling the counter, but that's not the point, I want to be able to do this at a macro definition level (so I can apply it to the sagetex context).

Any ideas?

• can you make sage write something else eg \def\foo{x^2 - 2x - 3} rather than x^2 - 2x - 3 ? – David Carlisle Dec 7 '15 at 21:27
• This would be ideal and it seems like something that should be possible, but I can't seem to find a way to do so. – Jason Dec 7 '15 at 21:44
• hmm in that case I probably can't answer, I could make some guesses but it depends a bit on the timing of how sagetex hooks up the communication to sage. – David Carlisle Dec 7 '15 at 21:47
• After doing a whole lot more looking into this, I'm wondering if some trick using expansion would work? i.e. define the macro \foo and force it to expand the content (the \sage{f} part) at the definition stage, so that it expands and takes the input at that point instead of recalling \sage{f} each time? But I have no idea how to work with \expandafter \noexpand and all those commands too well...? – Jason Dec 8 '15 at 19:07
• almost certainly \sage is not expandable. – David Carlisle Dec 8 '15 at 20:31