How to update pure function?

Viewed 129

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.

3 Answers

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.

What about this?

def translate_func(f, c):
    return lambda x: f(x + c)

To be used like, e.g.:

import math


g = translate_func(math.sin, 10)
print(g(1) == math.sin(10 + 1))
# True

EDIT

Note that this design pattern of a function taking a function as a parameter and returning another function is quite common in Python and goes by the name of "function decoration", with an associated convenience syntax. See PEP318 for more info on it.

def transalte(f, c):
   def _inner(x):
      return f(x+c)
   return _inner
Related