Question

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!

Was it helpful?

Solution

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.)

OTHER TIPS

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))

You could reverse a dictionary two ways:

def reverse_mapping1(map):
    return {v:k for k, v in map.items()}

def reverse_mapping2(map):
    inverse = {}
    for k, v in map.iteritems():
        inverse[v] = inverse.get(v, [])
        inverse[v].append(k)
    return inverse

It isn't true functional programming, but it does offer a different way to think about solving the problem, which is what I think your teacher is trying to get at.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top