Search code examples
pythonfunctioncomposition

Python: A better way to write n compositions of a function?


I wrote a function "rep" that takes a function f and takes n compositions of f. So rep(square,3) behaves like this: square(square(square(x))). And when I pass 3 into it, rep(square,3)(3)=6561.

There is no problem with my code, but I was wondering if there was a way to make it "prettier" (or shorter) without having to call another function or import anything. Thanks!

def compose1(f, g):
    """Return a function h, such that h(x) = f(g(x))."""
    def h(x):
        return f(g(x))
    return h

def rep(f,n):
    newfunc = f
    count=1
    while count < n:
        newfunc = compose1(f,newfunc)
        count+=1
    return newfunc

Solution

  • If you're looking for speed, the for loop is clearly the way to go. But if you're looking for theoretical academic acceptance ;-), stick to terse functional idioms. Like:

    def rep(f, n):
        return f if n == 1 else lambda x: f(rep(f, n-1)(x))