More on functions

In python functions are ordinary objects. Therefore, a function can take functions as input, or return new functions, or both.

The function integral takes another function as an argument:

def integral(f, a, b):
    N = 1000
    dx = (b-a)/N
    return sum(f(a+dx*n) for n in xrange(N))*dx

The function mkAdder takes an integer an returns a function:

def mkAdder(n):
    def add(i):
        return i+n
    return add

add3 = mkAdder(3)
print add3(2)       #   5
print add3(8)       #  11

print mkAdder(5)(4) #   9

The last line may seem peculiar in that a single function (+) of two arguments (the two numbers being added) is written in terms of two functions which take one argument each.