Functional Programming in Python

Síguenos / Follow us!
Facebooktwitterlinkedinrssyoutubeinstagram

Introduction


Functional programming is a declarative programming paradigm where programs are constructed by applying and composing functions.

In this programming paradigm, functions are treated as first-class citizens, meaning that you can assign them to variables, store them in data structures, pass them as arguments, and even return them.

user@pc:~$ python
Python 3.9.5 (default, May 11 2021, 08:20:37) 
[GCC 10.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def talk(mood):  # This function (talk) returns a function depending on the mood
...     def shouting(sentence):
...             return sentence.upper() + "! :("
...     def nice(sentence):
...             return sentence + " :)"
...     def normal(sentence):
...             return sentence + "."
...     if mood=="shouting":
...             return shouting
...     elif mood=="nice":
...             return nice
...     else:
...             return normal
... 
>>> myConversation = talk("shouting") # myConversation is a variable that has been assigned a function and you can use it like a normal function!
>>> myConversation("You are stupid")
YOU ARE STUPID! :(
def factors(n):
    return [x for x in range(1,n+1) if n % x == 0]

def areaCircle(r): return math.pi * (r ** 2)

def apply_function(x, func):
    """It receives a function, executes it, and returns its result"""
    return func.__name__ + "( " + str(x) + " ) = " + str(func(x))

if __name__ == '__main__':
	myListFunctions = [factors, math.factorial, areaCircle] # We store three functions in a list.
	for f in myListFunctions:
		print(apply_function(5, f), end=". ") # We pass f as an argument.

factors( 5 ) = [1, 5]. factorial( 5 ) = 120. areaCircle( 5 ) = 78.53981633974483.

List Comprehension


List Comprehension is a very concise, powerful, and elegant way of creating lists in Python.

The syntax is as follows: myNewList = [expression for element in iterable if condition == True]

user@pc:~$ python
Python 3.9.5 (default, May 11 2021, 08:20:37) 
[GCC 10.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> [i for i in range(1, 10)] 
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [i**2 for i in range(1, 10)] 
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [i % 3 for i in range(1, 10)]
[1, 2, 0, 1, 2, 0, 1, 2, 0]
>>> [i**2 for i in range(1, 10) if i<5] # The condition is like a filter that only lets pass or accepts the items that valuate to True (i=1...4).
[1, 4, 9, 16]
>>> fruits=['apples','oranges','bananas','mangoes','grapes','strawberry']
>>> [word.upper() for word in fruits]
['APPLES', 'ORANGES', 'BANANAS', 'MANGOES', 'GRAPES', 'STRAWBERRY']
>>> [len(word) for word in fruits]
[6, 7, 7, 7, 6, 10]
>>> [len(word) for word in fruits if word.startswith("a")]
[6]
>>> [word.upper() for word in fruits if len(word)==7]
['ORANGES', 'BANANAS', 'MANGOES']
>>> [word.capitalize() for word in fruits if "o" in word]
['Oranges', 'Mangoes']

Lambda functions


A lambda function is a small anonymous function. It is sometimes convenient to define an anonymous function on the fly, without bothering to give it a name.

        x = lambda a, b: a + b # It is the sum function.
	print(x(5, 6)) # It returns 11.
	y = lambda a, b: a if a > b else b # It returns the element with the highest value.
	print(y(2, 3)) # It returns 3.
	z = lambda a, b: (b, a) # It swaps its two arguments.
	print(z(5, 9)) # (9, 5)

Map, Filter, and Reduce

Compártelo / Share it!
Facebooktwitterredditpinterestlinkedinmail

Author: Anawim

I am a social activist. I have two Bachelor's degrees, Maths and Computer & Software Engineering. I also have a Ph.D. in Psychology. I have written nine published books, four scientific articles, and five scientific presentations. I simply want to contribute to making a difference where it counts, so that we make the world a better, more sustainable, prosperous, and fairer place. I am always willing to give free talks and lectures about the social problems that exist in our world today.

Leave a Reply

Your email address will not be published. Required fields are marked *