Ask Your Question
1

how to inject a function?

asked 2017-10-19 10:53:13 -0600

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.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
0

answered 2017-10-19 19:21:25 -0600

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.)

edit flag offensive delete link more

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 ( 2017-10-20 05:39:21 -0600 )edit

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 ( 2017-10-20 06:00:41 -0600 )edit

Thanks, that's good to know.

Claude Brisson gravatar imageClaude Brisson ( 2017-10-20 07:36:59 -0600 )edit

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: 2017-10-19 10:53:13 -0600

Seen: 46 times

Last updated: Oct 19