4

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.

Ikuyasu
  • 441
  • 1
  • 4
  • 8

2 Answers2

3

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)
Samuel Lelièvre
  • 3,212
  • 1
  • 14
  • 27
2

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)
David Scholz
  • 8,421
  • 12
  • 19
  • 34