Functional programming is a paradigm that treats computation as the evaluation of mathematical functions and avoids shared and mutable data.
Programming is done with expressions or declarations instead of statements.
Functions as variables
square = lambda x: x**2
print(square) # <function <lambda> at 0x000002131C8E7BF8>
print(square(2)) # 4
Apply functions to all elements
result = []
for x in data:
y = square(x)
result.append(y)
result = map(square, data)
result = [square(x) for x in data]
Keep or discard elements in a collection
result = []
for x in data:
if is_even(x):
result.append(x))
result = filter(is_even, data)
result = [x for x in data if is_even(x)]
Aggregate elements in a collection to produce a single result
result = 0
for x in data:
result += x
from functools import reduce
result = reduce(add, data, 0)
Functions can be used as return value
def greeter():
return lambda: "Hello world"
print(greeter)
# <function greeter at 0x0000022A1FC99D08>
print(greeter())
# <function greeter.<locals>.<lambda> at 0x0000022A1FC998C8>
print(greeter()())
# Hello world
Inner functions can use variables from parent function
def counter():
i = 0
def increment():
nonlocal i
i += 1
return i
return increment
count = counter()
print(count()) # 1
print(count()) # 2
Inner functions can use parameters from parent function
def pow(exp):
return lambda x: x**exp
square = pow(2)
print(square(3)) # 9
def load_documents(data_folder):
categories = os.listdir(data_folder)
def list_document_paths(category):
cat_folder = path.join(data_folder, category)
file_paths = [path.join(cat_folder, f) for f in os.listdir(cat_folder)]
doc_paths = [f for f in file_paths if f.endswith(".txt")]
return doc_paths
documents = [
InputDocument(document_path, category)
for category in categories
for document_path in list_document_paths(category))
]
return documents
def training(documents):
tokenized_docs = [tokenize(doc) for doc in documents]
preprocessed_docs = [preprocess(doc) for doc in tokenized_docs]
vocabulary = build_vocabulary(preprocessed_docs)
build_bow = lambda doc: assign_weights(vocabulary, doc)
bow_docs = [build_bow(doc) for doc in preprocessed_docs]
model = train_model(bow_docs)
return model, vocabulary