In this section, let's look at the functions that will return another function.
Let's take a high school example and try to explain the use of functions returning functions.
Our problem is we are given a cylinder of radius r and we would like to know the volume of it for different heights:
http://www.mathopenref.com/cylindervolume.html
Volume = area * height = pi * r^2 * h
The preceding formula gives the exact cubic units that will fill a cylinder.
Let's write a simple function to demonstrate the concept of a function returning a function. In addition, we will write a small piece of code to show the usage:
# 1. Let us define a function which will explain our # concept of function returning a function. def cylinder_vol(r): pi = 3.141 def get_vol(h): return pi * r**2 * h return get_vol # 2. Let us define a radius and find get a volume function, # which can now find out the volume for the given radius and any height. radius = 10 find_volume = cylinder_vol(radius) # 3. Let us try to find out the volume for different heights height = 10 print "Volume of cylinder of radius %d and height %d = %.2f cubic units" %(radius,height,find_volume(height)) height = 20 print "Volume of cylinder of radius %d and height %d = %.2f cubic units" %(radius,height,find_volume(height))
In step 1, we defined a function called cylinder_vol()
; it takes a single parameter, r
, radius.
In this function, we defined another function, get_vol()
. The get_vol()
function has access to r and pi, takes the height as an argument. For the given radius, r, which was the parameter to cylinder_vol()
, different heights were passed as a parameter to get_vol()
.
In step 2, we defined a radius; in this case, as ten and invoke the cylinder_vol()
function
with it. It returns the get_vol()
function, which we stored in a variable named find_volume
.
In step 3,
we invoked find_volume
with different heights, 10 and 20. Note that we didn't give the radius.
The output produced is as follows:
Volume of cylinder of radius 10 and height 10 = 3141.00 cubic units Volume of cylinder of radius 10 and height 20 = 6282.00 cubic units