Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update pure function?

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.

like image 736
Ziofil Avatar asked Dec 22 '22 21:12

Ziofil


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

like image 145
wim Avatar answered Dec 26 '22 00:12

wim