Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python programming functional vs. imperative code

So I'm currently in a class learning about the 3 major programming paradigms. I know that python uses both the functional and imperative paradigms. I was looking for a short sample code in python of each of these paradigms to better understand this before my exam tomorrow. Thank you!

like image 917
Bobcat88 Avatar asked Feb 20 '14 00:02

Bobcat88


2 Answers

Given L = [1, 2, 3, 4, 5] we can compute the sum in two ways.

Imperative:

sum = 0
for x in L:
    sum += x

Functional (local function):

def add(x, y):
    return x + y
sum = reduce(add, L)

Functional (lambda expression):

sum = reduce(lambda x, y: x + y, L)

(Of course, the built in sum function would effectively do the same thing as either of these.)

like image 153
Timothy Shields Avatar answered Sep 23 '22 19:09

Timothy Shields


One way to think of the difference between imperative and functional paradigms is that with imperative you have to explicitly code the order of your operations (I'm using very loose language here to make it simple for you). In contrast, with functional programming you are not defining the sequence but rather you are declaring what you are trying to model (this is why it is sometimes referred to as declarative style of programming).

So in the example below, if I want to determine which numbers are even in the list I have to explicitly code the loop and check whether each number is even or not when coding imperatively. I didn't need to do that in the functional example. In that example, I just defined what it means for a number to be even and then I just applied this abstraction/function to the list. A simple one liner.

There are more differences between the two paradigms but this should give you an idea.

Imperative:

naturalNumbers = [0,1,2,3,4,5,6,7,8,9]

def printEvenNumbers (listOfNumbers):
    for x in listOfNumbers:
        if x % 2 == 0:
            print True
        else:
            print False

Functional:

def evenNumber (x):
    return (x % 2) == 0

print(map(evenNumber, naturalNumbers))
like image 45
M.K. Avatar answered Sep 20 '22 19:09

M.K.