First time here? Check out the FAQ!

Ask Your Question
1

How to return a list from callable symbolic expression

asked 11 years ago

Mark gravatar image

I was (wrongfully) expecting the return type of all of the following function calls to be the same, namely a list. Why does the callable symbolic expression (1) return a vector, and how to rewrite (1) such that it does return a list?

# (1)
sage: f(x) = [x,x]
# (2)
sage: g = lambda x: [x,x]
# (3)
sage: def h(x):
....:     return [x,x]

sage: type(f(x))
<class 'sage.modules.vector_symbolic_dense.Vector_symbolic_dense'>
sage: type(g(x))
<type 'list'>
sage: type(h(x))
<type 'list'>
Preview: (hide)

1 Answer

Sort by » oldest newest most voted
3

answered 11 years ago

Luca gravatar image

updated 11 years ago

If you type

sage: f??

You will see that the method .__call__ (responsible for the behaviour of evaluating f) is the one-liner

return vector([e(*args, **kwargs) for e in self])

This has been designed so that symbolic functions can safely be used in symbolic expressions in a meaningful way. For example, you can combine f with another symbolic function using the vector product operator *:

sage: f(x) = [x,x]
sage: f
x |--> (x, x)
sage: f * f
x |--> 2*x^2

This would not work with ordinary python lists.

There is no way around it. If you really only need to return a list, then an ordinary python function (like (2) or (3)) is probably enough. Or you can convert the output of f to a list like so:

sage: list(f(x))
Preview: (hide)
link

Comments

Can you provide me with an example of what you mean by 'unsafe' or 'not meaningful' if the callable symbolic expression would actually return what I have asked for, namely a list?

Mark gravatar imageMark ( 11 years ago )

Edited my answer to account for your comment.

Luca gravatar imageLuca ( 11 years ago )

(Maybe) that helps. Let me ask one for clarification. If I get you right, kind of your point is, that callable symbolic expression should allow for meaningful usage with symbolic operations like multiplication, addition a.s.o. But while a scalar product, as f*f may make sense (even though I wasn't even looking for that) the division f(x)/f(x) is also a symbolic operation, which does not make sense for me in case of vectors - although sage simply return f(x)/f(x) = 1 with my definition (1)

Mark gravatar imageMark ( 11 years ago )

This is due to the semantics of symbolic vectors in Sage, as it has been discussed in <http://ask.sagemath.org/question/2917/vector-division>. I agree that this kind of inverse of multiplication by a scalar is somewhat surprising, and that it does not seem to be documented anywhere.

Luca gravatar imageLuca ( 11 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

Stats

Asked: 11 years ago

Seen: 718 times

Last updated: Aug 17 '13