Ikuyasu
Ikuyasu

Reputation: 441

taking function as an input in SageMath

How do you make a function that takes a function as input? What I want to do is something like:

f(x) = log(x)
g(f, x) = x^2 * f(x)

g(f, 2) 
# Symbolic expression of x^2 * log(x)

I think I am looking for the way to create higher order function.

Upvotes: 4

Views: 450

Answers (2)

David Scholz
David Scholz

Reputation: 9856

We can create a python function that returns a symbolic function and takes two symbolic functions as an input.

Consider the following code.

g(x) = x^2
f(x) = log(x)

def foo(f, g, x):
    return g(x) * f(x)

z(x)=foo(g, f, x)

Take a look at it.

sage: z

which yields to the symbolic function

x |--> x^2*log(x)

Upvotes: 2

Samuel Lelièvre
Samuel Lelièvre

Reputation: 3453

Would using a lambda function for g work for you?

Here is a way to do that:

sage: f(x) = log(x)
sage: g = lambda u, v: v*2 * u(v)
sage: g(f, 2)
4*log(2)

Upvotes: 3

Related Questions