Functions as arguments to functions

arguments, function, python

Solution

`g` is passed as an argument to `diff2`. In `diff2`, that argument is called `f`, so inside `diff2` the name `f` refers to the function `g`. When `diff2` calls `f(x-h)` (and the other calls it does), it is calling `g`, and providing the argument.

In other words, when you do `diff2(g, t)`, you are telling `diff2` that `g` is the function to call. The arguments to `g` are provided in `diff2`:

f(x-h) # calls g with x-h as the argument
f(x)   # calls g with x as the argument
f(x+h) # calls g with x+h as the argument

If you called `diff2(g(t), t)`, you would be passing the result of `g(1.2)` as the argument. `g` would be called before calling `diff2`, and `diff2` would then fail when it tries to call `f`, because `f` would be a number (the value `g(1.2)`) instead of a function.

Problem

I saw this example in a Python book, which showcases how to use a function as an argument to another function: ``` def diff2(f, x, h=1E-6): r = (f(x-h) - 2*f(x) + f(x+h))/float(h*h) return r def g(t): return t**(-6) t = 1.2 d2g = diff2(g, t) print d2g ``` My question is, how does this script work without providing an argument to function g? The line in question is: ``` d2g = diff2(g,t) ``` Shouldn't it be done like: ``` d2g = diff2(g(t), t) ```

Original source