Ask Your Question
1

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

asked 4 years ago

vikahdv@gmail.com gravatar image

updated 4 years ago

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?

Preview: (hide)

4 Answers

Sort by » oldest newest most voted
4

answered 4 years ago

tmonteil gravatar image

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.

Preview: (hide)
link
2

answered 4 years ago

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.

Preview: (hide)
link
2

answered 4 years ago

eric_g gravatar image

updated 4 years ago

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.

Preview: (hide)
link
0

answered 4 years ago

Cyrille gravatar image

updated 4 years ago

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))
Preview: (hide)
link

Comments

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.

slelievre gravatar imageslelievre ( 4 years ago )

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 4 years ago

Seen: 914 times

Last updated: Dec 18 '20