Passing Functions as Arguments¶
Let us understand how to pass functions as arguments using Python as programming language.
- The function which takes other functions as arguments is typically called as higher order function and the function which is passed as argument is called as lower order function.
- You need to define all the functions you want to pass as argument for the higher order functions.
- For simple functionality, we can also pass unnamed functions or lambda functions on the fly. We will see as part of the next topic.
- Let us take the example of getting sum of integers, squares, cubes and evens related to passing functions as arguments.
Regular Functions
In [1]:
list(range(1, 10))
Out[1]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [2]:
list(range(1, 10, 2))
Out[2]:
[1, 3, 5, 7, 9]
In [3]:
list(range(1, 10, 3))
Out[3]:
[1, 4, 7]
In [4]:
def sum_of_integers(lb, ub):
total = 0
for i in range(lb, ub + 1):
total += i
return total
In [5]:
sum_of_integers(5, 10)
Out[5]:
45
In [6]:
def sum_of_squares(lb, ub):
total = 0
for i in range(lb, ub + 1):
total += i * i
return total
In [7]:
sum_of_squares(5, 10)
Out[7]:
355
In [8]:
def sum_of_cubes(lb, ub):
total = 0
for i in range(lb, ub + 1):
total += i * i * i
return total
In [9]:
sum_of_cubes(5, 10)
Out[9]:
2925
In [10]:
def sum_of_evens(lb, ub):
total = 0
for i in range(lb, ub + 1):
total += i if i % 2 == 0 else 0
return total
In [11]:
sum_of_evens(5, 10)
Out[11]:
24
Using Functions as arguments
In [12]:
def my_sum(lb, ub, f):
total = 0
for e in range(lb, ub + 1):
total += f(e)
return total
In [13]:
def i(n): return n
In [14]:
def sqr(n): return n * n
In [15]:
def cube(n): return n * n * n
In [16]:
def even(n): return n if n % 2 == 0 else 0
In [17]:
my_sum(5, 10, i)
Out[17]:
45
In [18]:
my_sum(5, 10, sqr)
Out[18]:
355
In [19]:
my_sum(5, 10, cube)
Out[19]:
2925
In [20]:
my_sum(5, 10, even)
Out[20]:
24