substituting into a Sage/Python function

62 views
Skip to first unread message

john_perry_usm

unread,
Jun 14, 2016, 4:07:30 PM6/14/16
to sage-support
Hi!

When demonstrating stuff in class, I often want the variable to be an argument to a function:

def test_subs(f, a, x=x):
 
print f(a)

This works if f is a function. If f is not a function, Sage issues a DeprecationWarning (rightly, IMHO). So we could try this:

def test_subs(f, a, x=x):
 
print f(x=a)

...which sort of works, but not with a different variable:

sage: f = t^2 + 2
sage
: test_subs(f, 1, t)
t
^2 + 2

Another way to make it work with expressions is by dictionary substitution:

def test_subs(f, a, x=x):
 
print f({x:a})

...and that now works with expressions, but not with functions:

sage: f(t) = t^2 + 2
sage
: test_subs(f, 1, t)
...
TypeError: no canonical coercion from <type 'dict'> to Callable function ring with argument t

I can fix this with a try/except block, but when discussing it with a much wiser colleague he pointed out that it made the learning curve rather steep for kids who can barely do calculus.

Is there a smarter way to do substitution, so that a function doesn't have to worry about whether the input is an expression or an honest-to-goodness function?

Ralf Stephan

unread,
Jun 16, 2016, 3:25:28 AM6/16/16
to sage-support
On Tuesday, June 14, 2016 at 10:07:30 PM UTC+2, john_perry_usm wrote:
sage: f(t) = t^2 + 2
sage
: test_subs(f, 1, t)
...
TypeError: no canonical coercion from <type 'dict'> to Callable function ring with argument t


I am not sure why you didn't try:
sage: test_subs(f(t),1,t)
3

Of course it cannot work if you don't give a dependent var. 

john_perry_usm

unread,
Jun 16, 2016, 7:37:25 AM6/16/16
to sage-support

I am not sure why you didn't try:
sage: test_subs(f(t),1,t)
3

I know that works! Part of the point is to demonstrate that we can't always count on a parameter having the type we assume. If the answer is simply, "Use functions. Period." then I would pass that advice on.

john_perry_usm

unread,
Jun 16, 2016, 8:51:00 AM6/16/16
to sage-support
Actually, your answer stimulated a much better solution (IMHO).
def test_subs(f, a, x=x):
    f
(x) = f
   
print f(a)

Thanks for the stimulating thought.
Reply all
Reply to author
Forward
0 new messages