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 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']
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)
![There are two ways to write error-free programs; only the third one works.](../images/functional Programming.jpeg)
import math
def areaCircle(r):
return round(math.pi * (r**2), 2)
def areaTriangle(b, h):
return (b * h)/2
if __name__ == '__main__':
myList = [x for x in range(1, 10)]
print(myList) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Let's compute the factorial of a list of numbers.
myListFactorial = map(math.factorial, myList)
print(list(myListFactorial)) # [1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
fruits=['apples','oranges','bananas','mangoes','grapes','strawberry']
# Let's calculate the length of each word from a list.
myLenFruits = map(len, fruits)
print(list(myLenFruits)) # [6, 7, 7, 7, 6, 10]
# Next, we are going to reverse each word from our fruits list.
myReverseFruits = map(lambda s: s [::-1], fruits)
print(list(myReverseFruits))
[‘selppa’, ‘segnaro’, ‘sananab’, ‘seognam’, ‘separg’, ‘yrrebwarts’]
print(", ".join(map(str, [1, 2, 3, 4, 5]))) # The result printed out is 1, 2, 3, 4, 5
The join() string method returns a string by taking all items in an iterable and joining them. The syntax is as follows: string.join(iterable). A string must be specified as the separator.
>>> list(map(str, [1, 2, 3, 4, 5])) ['1', '2', '3', '4', '5']
print(", ".join(map(str.capitalize, fruits)))
# It returns Apples, Oranges, Bananas, Mangoes, Grapes, Strawberry.
# The capitalize() method returns a copy of the original string where the first character is upper case, and the rest is lower case.
myBase = [5, 14, 9, 12]
myHeight = [8, 10, 12, 15]
print(list(map(areaCircle, myList))) # [3.14, 12.57, 28.27, 50.27, 78.54, 113.1, 153.94, 201.06, 254.47]
print(list(map(areaTriangle, myBase, myHeight))) # [20.0, 70.0, 54.0, 90.0]
Iterable is any Python object which can be looped or iterated over in a for-loop. Objects like lists, tuples, sets, dictionaries, and strings are iterable.
mySentence = "I love apples, bananas, and mangoes, but I am crazy about apples."
for word in ['apples','oranges','bananas','mangoes','grapes','strawberry']:
vals = list(map(lambda f: f(word), (len, mySentence.count)))
print(vals) # [6, 2] [7, 0] [7, 1] [7, 1] [6, 0] [10, 0]
import statistics
def factors(n): # It computes all factor of n
return [x for x in range(1,n+1) if n % x == 0]
if __name__ == '__main__':
myEvenList = filter(lambda n: n%2==0, myList)
myOddList = filter(lambda n: n%2!=0, myList)
myPrimeList = filter(lambda n: factors(n) == [1,n], myList) # It filters away those numbers that are not prime.
print(list(myEvenList)) # [2, 4, 6, 8]
print(list(myOddList)) # [1, 3, 5, 7, 9]
print(list(myPrimeList)) # [2, 3, 5, 7]
lista = ["redivider", "amazing", "deified", "palindrome", "whatever", "civic", "radar", "level", "rotor", "kayak"]
palindromes = list(filter(lambda word: word == word[::-1], lista)) # It filters away those words that are not palindromes.
print(list(palindromes)) # ['redivider', 'deified', 'civic', 'radar', 'level', 'rotor', 'kayak']
average = statistics.mean(myList) # It calculates the mean or average of myList.
print(list(filter(lambda n: n <= average, myList))) # It prints out all the elements of myList that are less than or equal to average.
from functools import reduce
# You need to import functools to use the reduce function.
print(reduce(lambda x, y:x+y, myList))
# It returns the sum of all the items in myList, 45.
print(reduce(lambda a, b: a if a > b else b, myList))
# It returns the list's maximum value, 9.