Site icon Meccanismo Complesso

Python Lessons – 6.1 Functional Programming

Python Lesson - 6.1 Functional Programming m
Python Lesson - 6.1 Functional Programming

Functional Programming

Functional programming is a programming style based exclusively on the use of functions.

An important role of this type of programming is played by higher order functions. This kind of functions take other functions as arguments, or return functions.

def increase(x):
    return x + 1;

def apply(func, y):
    return func(y)


if you run it, you get:


Pure Functions

Functional programming is based on the exclusive use of pure functions. The pure functions have no side effects and the return value depends only on their arguments. (No variables external to the function are used).

This is how mathematical functions work, for example cos (x) is a pure function.

Let’s look at two examples of a pure and a no function.

def pure(x,y):
    return x + y

lista = []
def notpure(x):

The use of pure functions has both advantages and disadvantages. Pure functions are easier to understand and test, and more efficient. In fact, the result of these functions can be stored within variables and reused later without calling the function again. This technique is called memoization. Moreover this type of programming lends itself well for parallel calculation.

The disadvantages are those that often many simple operations performed by functions not pure (we think to the I / O management) can become extremely complex if implemented only with pure functions.

⇐ Go to Python Lesson 5.8 – Some useful functions for numbers and strings

Go to Python Lesson 6.2 – Lambda functions ⇒

Exit mobile version