Programmazione funzionale in Python
Versione italiana
La programmazione funzionale è un paradigma di programmazione che tratta la computazione come la valutazione di funzioni matematiche e evita l'uso di stati e dati mutabili. Python, pur non essendo un linguaggio puramente funzionale, supporta molti concetti di programmazione funzionale. Di seguito sono riportati alcuni dei concetti chiave della programmazione funzionale in Python:
1. Funzioni di ordine superiore (map()
, filter()
, reduce()
)
Le funzioni di ordine superiore sono funzioni che prendono altre funzioni come argomenti o restituiscono funzioni come risultato. In Python, le funzioni map()
, filter()
, e reduce()
sono esempi di funzioni di ordine superiore.
map()
: Applica una funzione a tutti gli elementi di un iterabile (come una lista) e restituisce un iteratore che produce i risultati.
# Esempio di map()
numeri = [1, 2, 3, 4, 5]
quadrati = map(lambda x: x**2, numeri)
print(list(quadrati)) # Output: [1, 4, 9, 16, 25]
filter()
: Filtra gli elementi di un iterabile in base a una condizione specificata da una funzione.
# Esempio di filter()
numeri = [1, 2, 3, 4, 5]
pari = filter(lambda x: x % 2 == 0, numeri)
print(list(pari)) # Output: [2, 4]
reduce()
: Applica una funzione cumulativa a una sequenza di elementi, riducendo la sequenza a un singolo valore.reduce()
è parte del modulofunctools
.
from functools import reduce
# Esempio di reduce()
numeri = [1, 2, 3, 4, 5]
somma = reduce(lambda x, y: x + y, numeri)
print(somma) # Output: 15
2. List comprehension e generator expression
Le list comprehension e le generator expression sono costrutti sintattici che permettono di creare liste o generatori in modo conciso.
- List comprehension: Permette di creare una lista applicando un'espressione a ciascun elemento di un iterabile.
# Esempio di list comprehension
numeri = [1, 2, 3, 4, 5]
quadrati = [x**2 for x in numeri]
print(quadrati) # Output: [1, 4, 9, 16, 25]
- Generator expression: Simile alla list comprehension, ma restituisce un generatore invece di una lista. I generatori sono iterabili che producono valori on-the-fly, risparmiando memoria.
# Esempio di generator expression
numeri = [1, 2, 3, 4, 5]
quadrati = (x**2 for x in numeri)
print(list(quadrati)) # Output: [1, 4, 9, 16, 25]
3. Generatori (yield
)
I generatori sono funzioni speciali che producono una sequenza di valori utilizzando la parola chiave yield
. A differenza delle funzioni normali, i generatori mantengono il loro stato tra le chiamate, permettendo di generare valori in modo lazy (on-demand).
# Esempio di generatore con yield
def generatore_numeri():
n = 1
while n <= 5:
yield n
n += 1
# Utilizzo del generatore
gen = generatore_numeri()
for numero in gen:
print(numero) # Output: 1 2 3 4 5
I generatori sono particolarmente utili quando si lavora con grandi quantità di dati, poiché non caricano tutti i dati in memoria contemporaneamente, ma li producono uno alla volta.
English version
Functional Programming in Python
Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids the use of state and mutable data. Python, while not a purely functional language, supports many functional programming concepts. Here are some of the key concepts of functional programming in Python:
1. Higher-order functions (map()
, filter()
, reduce()
)
Higher-order functions are functions that take other functions as arguments or return functions as results. In Python, the functions map()
, filter()
, and reduce()
are examples of higher-order functions.
map()
: Applies a function to all elements of an iterable (such as a list) and returns an iterator that produces the results.
# map() example
numbers = [1, 2, 3, 4, 5]
squares = map(lambda x: x**2, numbers)
print(list(squares)) # Output: [1, 4, 9, 16, 25]
filter()
: Filters the elements of an iterable based on a condition specified by a function.
# filter() example
numbers = [1, 2, 3, 4, 5]
even = filter(lambda x: x % 2 == 0, numbers)
print(list(even)) # Output: [2, 4]
reduce()
: Applies a cumulative function to a sequence of elements, reducing the sequence to a single value.reduce()
is part of thefunctools
module.
from functools import reduce
# Example of reduce()
numbers = [1, 2, 3, 4, 5]
sum = reduce(lambda x, y: x + y, numbers)
print(sum) # Output: 15
2. List Comprehensions and Generator Expressions
List comprehensions and generator expressions are syntactic constructs that allow you to create lists or generators in a concise way.
- List comprehension: Allows you to create a list by applying an expression to each element of an iterable.
# List Comprehension Example
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares) # Output: [1, 4, 9, 16, 25]
- Generator expression: Similar to list comprehension, but returns a generator instead of a list. Generators are iterables that produce values on-the-fly, saving memory.
# Generator expression Example
numbers = [1, 2, 3, 4, 5]
squares = (x**2 for x in numbers)
print(list(squares)) # Output: [1, 4, 9, 16, 25]
3. Generators (yield
)
Generators are special functions that produce a sequence of values using the yield
keyword. Unlike regular functions, generators maintain their state between calls, allowing you to generate values lazy (on-demand).
# Generator example with yield
def number_generator():
n = 1
while n <= 5:
yield n
n += 1
# Using the generator
gen = number_generator()
for number in gen:
print(number) # Output: 1 2 3 4 5
Generators are especially useful when working with large amounts of data, because they do not load all the data into memory at once, but produce them one at a time.
Commenti
Posta un commento