0

I am having trouble creating a higher order function in python that applies a function f, n times to generate a new function h, as its return value.

def compile(f, n)
    # h is a function, f applied n times
    ...
    return h

new = compile(lambda x: 2*x, 3)
new(4) == 32 # new(4) == 2(2(2(4)))
Will Ness
  • 70,110
  • 9
  • 98
  • 181
user9873466
  • 95
  • 1
  • 5
  • 1
    please read [ask] – Julien May 31 '18 at 02:20
  • Unrelated to your question: `compile` is a Python builtin function, so you probably shouldn't write your own function with that name. Doing so will mask the builtin function (and might cause awkward bugs if you wanted to use the original `compile`). – Blckknght May 31 '18 at 02:47

2 Answers2

3

Since Python's functions are first-class citizens, a function can itself define a new function and return it. Defining a function inside a function can be done with def in the same way it would be in you top scope.

As a sidenote, I recommend you do not use compile as a function name as it does not accurately reflect what you are trying to do, which is called function composition, as well as overwrite the builtin function compile.

def compose_with_self(f, n):
    def composed(arg):
        for _ in range(n):
            arg = f(arg)
        return arg
    return composed

Example:

def add_one(x):
    return x + 1

add_three = compose_with_self(add_one, 3)

print(add_three(1)) # 4
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
1

You can do this easily using recursion

  • if n is zero, simply return x
  • otherwise, n is at least 1, apply f(x) to the recursive result compile (f, n - 1)

We can encode this in Python easily

def compile (f, n):
  return lambda x: \
    x if n is 0 else compile (f, n - 1) (f (x))

double_thrice = compile (lambda x: 2 * x, 3)

print (double_thrice (4))
# 32
Mulan
  • 129,518
  • 31
  • 228
  • 259