Member-only story
Map, Reduce, and Filter in Declarative and Imperative Programming Styles in Python
Learn about high-level functions in Python with Declarative & Imperative programming approaches
What is Declarative Programming?
It is a programming approach in which a program is written with a view of describing WHAT it has to do / WHAT problem it is intended to solve rather than how it should solve the problem.
Declarative programming approaches do not describe the control flow in detail.
For example, in order to sort a list in Python, the declarative programming approach can be used as follows :
nums = [2,5,4,1,6,3]nums.sort()# Sorts the list to: [1,2,3,4,5,6]
What is Imperative Programming?
It is a programming approach where the program’s control flow is explicitly written.
It mentions HOW a problem should be solved / HOW a task should be done.
For example, the imperative programming approach to sort a list by Bubble sort can be as follows:
nums = [2,5,4,1,6,3]def bubblesort(elements):
swapped = False
for n in range(len(elements)-1, 0, -1):
for i in range(n):
if elements[i] > elements[i + 1]:
swapped = True
elements[i], elements[i + 1] = elements[i + 1], elements[i]
if not swapped:
returnbubblesort(nums)# Sorts the list to: [1,2,3,4,5,6]
Higher Order Functions in Python
These functions take an iterable (tuple, list, etc.) as a parameter and return another iterable as an output.
Let’s talk about three higher-order functions in Python and break them down.
Map Function
The map
function takes an iterable and returns a map object (another iterable) after applying a given function.