First time here? Check out the FAQ!

Ask Your Question
1

how to inject a function?

asked 7 years ago

Claude Brisson gravatar image

One can inject variables using the inject_variable utility function:

from sage.misc.misc import inject_variable
inject_variable('foo', 'bar')

Now, how would it be possible to inject a function?

The context in which it is needed is the following one: I'm injecting the result of a resolution in the context as follow:

sol = solve([ ... ], f, g)
for s in sol[0]:
  inject_variable(str(s.lhs()),s.rhs());

but now I need to define f and g as parametrized by i, and things like inject_variable(str(s.lhs())+'(i)',s.rhs()) don't seem to work.

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
0

answered 7 years ago

dan_fulea gravatar image

It is not simple to understand the question.

Is for instance the following code injecting a function?

from sage.misc.misc import inject_variable
inject_variable( 'foo', lambda x, y: "%s is entering %s's bar" % ( x, y ) )
foo( 'Fangoraro', 'Harry' )

Result:

"Fangoraro is entering Harry's bar"

Also, one can inject many variables by using a fixed prefix and a numbered running suffix, e.g.

sage: for count in [1..999]:
....:     digits = count.digits( padto=3 )
....:     digits . reverse()
....:     inject_variable( "sol_%s" % ( ''.join( [str(d) for d in digits ] ) ), count^3 )
....:

This initializes a lot of variables, among them:

sage: sol_123
1860867
sage: sol_001
1
sage: sol_002
8

But why not use dictionaries instead? In fact, solve may even give the result in form of a dictionary, just use solution_dict=True. (And merge together all solution dictionaries with different keys. And keys may even be numbers, strings, tuples, or other immutable objects.)

Preview: (hide)
link

Comments

Thanks. The lambda construct did the trick. Numbering running suffixes are not applicable in my case, neither are dictionaries since positional parameters aren't yet functions at the time of the solving.

Claude Brisson gravatar imageClaude Brisson ( 7 years ago )

In this case, it may be that using exec and/or eval is also an alternative to generate dynamic code:

sage: del(foo)
sage: exec( """def foo(x,y): return "%s is entering %s's bar" % (x,y) """ )
sage: foo( 'Fangoraro', 'Harry' )
"Fangoraro is entering Harry's bar"
dan_fulea gravatar imagedan_fulea ( 7 years ago )

Thanks, that's good to know.

Claude Brisson gravatar imageClaude Brisson ( 7 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: 7 years ago

Seen: 934 times

Last updated: Oct 20 '17