I'm trying to do the following: I want to write a function translate(f, c)
that takes a given function f
(say we know f
is a function of a single variable x
) and a constant c
and returns a new function that computes f(x+c)
.
I know that in Python functions are first-class objects and that I can pass f
as an argument, but I can't think of a way to do this without passing x
too, which kind of defeats the purpose.
The trick is for translate to return a function instance.
def translate(f, c):
def func(x):
return f(x + c)
return func
Now the variable x
is "free", and the names f
and c
are coming from an enclosing scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With