# Quickly recalling the definition of a temporary function to make minor edits?

Suppose you're working with the sage console primarily as a calculator, and define some temporary shorthand function, such as,

sage: R = GF(751)
sage: def f(x):
....:    return R(x^3-x+188)


After I've used this f several times, I may want to change the output to something similar, like x^3-x+376. Is there a quick way to recall the definition of f within the console so that I can edit in the minor change, instead of having to define a new function?

edit retag close merge delete

Sort by » oldest newest most voted

From the console, type d (the first letter of def f(x):), followed by the up arrow to browse the history. If you typed too many commands starting with d between the definition of f and the current time, you can type a larger prefix, like de or def f follwed with the up arrow.

more Another option, in addition to @tmonteil's nice answer: once you've defined f, you can do this:

sage: ed f


(%ed f or edit(f) should accomplish the same thing.) This will open up an editor window (editor based on the setting of the EDITOR environment variable, which of course should be emacs). Then you can modify f however you like.

more

The double question mark will show the code of f:

sage: f??
Signature: f(x)
Source:
def f(x):
return R(x**Integer(3)-x+Integer(188))
File:      ~/sage/9.3.develop/<ipython-input-2-567a043781c3>
Type:      function


Note that Sage's preparser has turned x^3-x+188 into x**Integer(3)-x+Integer(188).

EDIT: the above does not answer to the question: it's a quick way to recall the definition of f but it does not allow to edit it. See @tmonteil 's answer for this.

more

I think that the simple way is to add a condition in the definition.

R=2
def f(x,n):
if n==1 :
return R*(x^3-x+188)
else :
return R*(x^3-x+376)

show(f(2,1),',',f(2,2))

more

The question is about how to access and modify a previously defined function in the Sage REPL, when one wants to, not about adding an additional parameter or making the function behave differently depending on how many times it has been called.