First time here? Check out the FAQ!

Ask Your Question
1

How does SageMath assign to a function call without raising an exception?

asked 8 years ago

Pretty Antlers gravatar image

I can assign some functions to a function call like this:

sage: f(x) = cos(x)

But I can't assign other functions like this:

sage: f(x) = lambda x: 1
...
TypeError

which happens to raise a different exception in Python:

>>> f(x) = lambda x: 1
...
SyntaxError: can't assign to function call

So, how does the SageMath interpreter change the behavior of Python?

Preview: (hide)

2 Answers

Sort by » oldest newest most voted
0

answered 8 years ago

slelievre gravatar image

The input f(x) = cos(x) is preparsed by Sage as follows.

sage: preparse('f(x) = cos(x)')
'__tmp__=var("x"); f = symbolic_expression(cos(x)).function(x)'

The following definition

sage: f = lambda x: 1

is synonymous with

sage: def f(x): return 1

If you want a symbolic function returning 1, see the discussion at

https://groups.google.com/d/topic/sag...

Preview: (hide)
link
1

answered 8 years ago

tmonteil gravatar image

When you write f(x) = cos(x), you define a symbolic expression. If you want to define a Python function, just do

sage:  f = lambda x: 1
Preview: (hide)
link

Comments

The syntax f(x) = something is invalid in Python and SageMath uses iPython, so what kind of wizardry does SageMath use to make it valid?

Pretty Antlers gravatar imagePretty Antlers ( 8 years ago )
1

You can see it by means of the function preparse, which shows the action of Sage's preparser before moving to Python:

sage: preparse("f(x) = cos(x)")
'__tmp__=var("x"); f = symbolic_expression(cos(x)).function(x)'
eric_g gravatar imageeric_g ( 8 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: 8 years ago

Seen: 1,918 times

Last updated: Mar 20 '16