Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct such a functional-programming tool in Python?

I want a function named times(), in order to make:

times(func,2) equivalent to lambda x:func(func(x))

and times(func,5) equivalent to lambda x:func(func(func(func(func(x)))))

Is there such a tool in Python? What would the code looks like if I want to write it by myself?

Thanks!

like image 380
Hanfei Sun Avatar asked Jul 20 '12 23:07

Hanfei Sun


1 Answers

I'd suggest to call this power(), since this is actually the nth power of a function. There is no such thing in the standard library, but you can easily implement it yourself:

def power(f, n):
    def wrapped(x):
        for i in range(n):
            x = f(x)
        return x
    return wrapped
like image 124
Sven Marnach Avatar answered Sep 22 '22 12:09

Sven Marnach