SlideShare a Scribd company logo
+ =f(x)
Python Functional Programming
Python Functional Programming
Functional Programming by Wikipidia:
“Functional programming is a programming paradigm that treats
computation as the evaluation of mathematical functions and avoids
state and mutable data". In other words, functional programming
promotes code with no side effects, no change of value in
variables. It oposes to imperative programming, which enfatizes
change of state”.
Python Functional Programming
What this means?
● No mutable data (no side effect).
● No state (no implicit, hidden state).
Once assigned (value binding), a variable (a symbol) does not change its value.
All state is bad? No, hidden, implicit state is bad.
Functional programming do not eliminate state, it just make it visible and explicit
(at least when programmers want it to be).
● Functions are pure functions in the mathematical sense: their output depend only
in their inputs, there is not “environment”.
● Same result returned by functions called with the same inputs.
Python Functional Programming
What are the advantages?
● Cleaner code: "variables" are not modified once defined, so we don't have to
follow the change of state to comprehend what a function, a, method, a class, a
whole project works.
● Referential transparency: Expressions can be replaced by its values. If we call a
function with the same parameters, we know for sure the output will be the same
(there is no state anywhere that would change it).
There is a reason for which Einstein defined insanity as "doing the same thing over
and over again and expecting different results".
Python Functional Programming
Advantages enabled by referential transparence
● Memoization
○ Cache results for previous function calls.
● Idempotence
○ Same results regardless how many times you call a function.
● Modularization
○ We have no state that pervades the whole code, so we build our project with
small, black boxes that we tie together, so it promotes bottom-up
programming.
● Ease of debugging
○ Functions are isolated, they only depend on their input and their output, so
they are very easy to debug.
Python Functional Programming
Advantages enabled by referential transparence
● Parallelization
○ Functions calls are independent.
○ We can parallelize in different process/CPUs/computers/…
We can execute func1 and func2 in paralell because a won’t be modified.
result = func1(a, b) + func2(a, c)
Python Functional Programming
Advantages enabled by referential transparence
● Concurrence
a. With no shared data, concurrence gets a lot simpler:
i. No semaphores.
ii. No monitors.
iii. No locks.
iv. No race-conditions.
v. No dead-locks.
Python Functional Programming
Python is a multi paradigm programming language. As a Python
programmer why uses functional programming in Python?
Python is not a functional language but have a lot of features that enables us to
applies functional principles in the development, turning our code more elegant,
concise, maintanable, easier to understand and test.
Python Functional Programming
Don’t Update, Create - String
name = 'Geison'
name = '{0} Flores'.format(name)
FIRSTNAME = 'Geison'
LASTNAME = '{0} Flores'.format(FIRSTNAME)
NAME = '{0} {1}'.format(FIRSTNAME, LASTNAME)
Python Functional Programming
Don’t Update, Create - Lists
years = [2001, 2002]
years.append(2003)
years += [2004, 2005]
years # [2001, 2002, 2003, 2004, 2005]
YEARS = [2001, 2001]
ALL_YEARS = YEARS + [2003] + [2004, 2005]
Python Functional Programming
Don’t Update, Create - Dict
ages = {'John': 30}
ages['Mary'] = 28
ages # {'John': 30, 'Mary': 28}
AGES = {'John': 30}
ALL_AGES = dict(AGES.itens() + {'Mary': 28}.itens())
Python Functional Programming
Higher Order Functions
Functions and methods are first-class objects in Python, so if you want to pass a
function to another function, you can just treat it as any other object.
def caller(f):
f()
def say_hello(name):
return 'Hello {0}'.format(name)
caller(say_hello)
Python Functional Programming
Higher Order Functions - Map
map(lambda word: word.upper(), ["milu", "rantanplan"])
# result ["MILU", "RANTANPLAN"]
def add_2(n):
n + 2
map(add_2, [1, 2, 3]) # result [3, 4, 5]
Python Functional Programming
Higher Order Functions - Filter
filter(lambda word: len(word) == 4, ["milu", "rantanplan"]) # result ["MILU"]
def greater_than_10(num):
return num > 10
filter(greater_than_10, range(15)) # result [11, 12, 13, 14, 15]
Python Functional Programming
Higher Order Functions - Reduce
import operator
reduce(operator.add, [1, 2, 3, 4, 5]) # result 15
def acumullator(a, b):
return len(a) + len(b)
reduce(acumullator, ["milu", "rantanplan"]) # result 14
reduce(lambda a,b: len(a) + len(b), ["milu", "rantanplan"]) # result 14
Python Functional Programming
Higher Order Functions - Reduce
from itertools import izip
list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
[list(x) for x in izip(list1, list2)] # result [[1, "a"], [2, "b"], [3, "c"]]
Python Functional Programming
Higher Order Functions - Closure
def add_x(x):
def adder(y):
return x + y
return adder
add_5 = add_x(5)
add_7 = add_x(7)
add_5(10) # result 15
add_7(10) # result 17
Python Functional Programming
Currying and Partial Functions
Higher-order functions enable Currying, which the ability to take a function that accepts n
parameters and turns it into a composition of n functions each of them take 1 parameter. A direct
use of currying is the Partial Functions where if you have a function that accepts n parameters then
you can generate from it one of more functions with some parameter values already filled in.
from functools import partial
plus = lambda a, b: a + b # defining a function that sums 2 numbers
plus(3, 5) # result 8
# curring calling partial function by supplying the first parameters with value 1
plus_one = partial(plus, 1)
# I can use the new function as normal
plus_one(5) # result 6
Python Functional Programming
Eager vs Lazy Evaluation
● Eager evaluation: expressions are calculated at the moment that variables is
assined, function called...
● Lazy evaluation: delays the evaluation of the expression until it is needed.
○ Memory efficient: no memory used to store complete structures.
○ CPU efficient: no need to calculate the complete result before returning.
○ Laziness is not a requisite for FP, but it is a strategy that fits nicely on
the paradigm(Haskell).
Python uses eager evaluation (but short-circuits && or ||).
Python generators are a mechanism for lazy evaluation.
Python arrays are not lazy, use enumarators when necessary.
Python Functional Programming
Recursion
Looping by calling a function from within itself. When you don’t have access to mutable
data, recursion is used to build up and chain data construction. This is because looping is
not a functional concept, as it requires variables to be passed around to store the state of
the loop at a given time.
● Purely functional languages have no imperative for-loops, so they use recursion a lot.
● If every recursion created an stack, it would blow up very soon.
● Tail-call optimization (TCO) avoids creating a new stack when the last call in a
recursion is the function itself.
● TCO is not implemented in Python.
● Unfortunarely following recursion style in Python has it’s own tax: Performance.
Python Functional Programming
Solving Python Lack of TCO(Tail Call Optimization)
# The functional solution have problens with big values
fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2)
# The iterative solution using generators works perfectly with large values
def fibs():
a = 0
b = 1
while True:
yield a
a, b = b, a + b
Python Functional Programming
FP in OOP?
It is possible do FP in OOP? Yes it is!
● OOP is orthogonal to FP.
● Well, at least in theory, because:
○ Typical OOP tends to emphasize change of state in objects.
○ Typical OOP mixes the concepts of identity and state.
○ Mixture of data and code raises both conceptual and practical problems.
● OOP functional languages: Scala, F#, ...
Python Functional Programming
A Pratical Example
Exercise: "What's the sum of the first 10 natural number whose square value is
divisible by 5?"
Imperative:
Functional:
n, num_elements, s = 1, 0, 0
while num_elements < 10:
if n**2 % 5 == 0:
s += n
num_elements += 1
n += 1
n #275
sum(filter(lambda x: x**2 % 5 == 0, range(1, 100))[:10])
Python Functional Programming
The last advice
Learn at least one functional language, it will open your mind to a new paradigm
becoming you a better programmer.
Some Functional Languages:
● Haskell
● ML (Standard ML, Objective Caml, ...)
● Scheme
● Erlang
● Scala
● Closure
● F#
Python Functional Programming
Conclusion
● As you can tell, Python helps you write in functional style but it doesn’t force
you to it.
● Writing in functional style enhances your code and makes it more self documented.
Actually it will make it more thread-safe also.
● The main support for FP in Python comes from the use of list conprehension,
lambdas, closures, iterators and generators, also from the modules functools and
itertools.
● Python still lack an important aspect of FP: Pattern Matching and Tails
Recursion.
● There should be more work on tail recursion optimization, to encourage developers
to use recursion.
● Any other thoughts?
Python Functional Programming
References
● http://en.wikipedia.org/wiki/Functional_programming
● http://www.cse.chalmers.se/~rjmh/Papers/whyfp.pdf
● http://docs.python.org/2/howto/functional.html
● http://www.youtube.com/watch?v=Ta1bAMOMFOI
● http://clojure.org/
● http://www.defmacro.org/ramblings/fp.html
Python Functional Programming
Contact me
● Email:
○ geisonfgf@gmail.com
● Skype
○ geisonfgf
● Facebook
○ http://www.facebook.com/geisonfgf
● Twitter
○ http://www.twitter.com/geisonfgf

More Related Content

PPSX
Modules and packages in python
TMARAGATHAM
 
PPTX
Python programming
Megha V
 
PDF
Introduction to python programming
Srinivas Narasegouda
 
PPTX
Functions in Python
Shakti Singh Rathore
 
PPT
Introduction to theory of computation
Vinod Tyagi
 
PPTX
Python basics
Jyoti shukla
 
PDF
What is Python Lambda Function? Python Tutorial | Edureka
Edureka!
 
PPTX
Memory management in python
Gaurav Aggarwal
 
Modules and packages in python
TMARAGATHAM
 
Python programming
Megha V
 
Introduction to python programming
Srinivas Narasegouda
 
Functions in Python
Shakti Singh Rathore
 
Introduction to theory of computation
Vinod Tyagi
 
Python basics
Jyoti shukla
 
What is Python Lambda Function? Python Tutorial | Edureka
Edureka!
 
Memory management in python
Gaurav Aggarwal
 

What's hot (20)

PPTX
Packages In Python Tutorial
Simplilearn
 
PDF
Artificial Intelligence Notes Unit 1
DigiGurukul
 
PDF
Recurrent Neural Networks, LSTM and GRU
ananth
 
DOC
C bitwise operators
Suneel Dogra
 
PPT
Functions in C++
Sachin Sharma
 
PPTX
Introduction to the basics of Python programming (part 1)
Pedro Rodrigues
 
PPTX
Beginning Python Programming
St. Petersburg College
 
PPTX
Introduction to-python
Aakashdata
 
PDF
Introduction to Machine learning with Python
Chariza Pladin
 
DOCX
Data Mining _ Weka
Ramya Krishna Puttur
 
PDF
File handling in Python
BMS Institute of Technology and Management
 
PDF
Python ppt.pdf
kalai75
 
ODP
Python_in_Detail
MAHALAKSHMI P
 
PDF
Lecture 01 introduction to compiler
Iffat Anjum
 
PPTX
Analysis of algorithm
Rajendra Dangwal
 
PPTX
Python Integrated Development Environment
TikendraPandey
 
PPT
Introduction to gdb
Owen Hsu
 
PPTX
Introduction to Python Basics Programming
Collaboration Technologies
 
PDF
SPL 2 | Algorithms, Pseudo-code, and Flowchart
Mohammad Imam Hossain
 
Packages In Python Tutorial
Simplilearn
 
Artificial Intelligence Notes Unit 1
DigiGurukul
 
Recurrent Neural Networks, LSTM and GRU
ananth
 
C bitwise operators
Suneel Dogra
 
Functions in C++
Sachin Sharma
 
Introduction to the basics of Python programming (part 1)
Pedro Rodrigues
 
Beginning Python Programming
St. Petersburg College
 
Introduction to-python
Aakashdata
 
Introduction to Machine learning with Python
Chariza Pladin
 
Data Mining _ Weka
Ramya Krishna Puttur
 
Python ppt.pdf
kalai75
 
Python_in_Detail
MAHALAKSHMI P
 
Lecture 01 introduction to compiler
Iffat Anjum
 
Analysis of algorithm
Rajendra Dangwal
 
Python Integrated Development Environment
TikendraPandey
 
Introduction to gdb
Owen Hsu
 
Introduction to Python Basics Programming
Collaboration Technologies
 
SPL 2 | Algorithms, Pseudo-code, and Flowchart
Mohammad Imam Hossain
 
Ad

Similar to Python functional programming (20)

PDF
Functional python
Jesué Junior
 
PDF
Rethink programming: a functional approach
Francesco Bruni
 
PDF
Introduction to Functional Programming
Francesco Bruni
 
PPTX
Functional Programming.pptx
KarthickT28
 
PPTX
Functional programming in python
Edward D. Weinberger
 
PDF
Functional programming in python
Edward D. Weinberger
 
PDF
Functional programming in Python 1st Edition David Mertz
kimmidalboc0
 
PDF
Functional programming in Python 1st Edition David Mertz
nkossivilana87
 
PDF
Functional Programming in Python
Haim Michael
 
PPT
An Overview Of Python With Functional Programming
Adam Getchell
 
PPTX
OOPS Object oriented Programming PPT Tutorial
amitnitpatna
 
PDF
Thinking in Functions: Functional Programming in Python
Anoop Thomas Mathew
 
PDF
Introduction to functional programming
Konrad Szydlo
 
PDF
Functional Programming inside OOP? It’s possible with Python
Carlos V.
 
PPTX
Advanced Programming_Basics of functional Programming.pptx
ManjishPal
 
PDF
Functional Programming #FTW
Adriano Bonat
 
PPTX
Seminar fp
VeerapatBoonvanich1
 
PDF
Functional programming in Python
Colin Su
 
PPTX
Why functional programming in C# & F#
Riccardo Terrell
 
PDF
Functional programming
ijcd
 
Functional python
Jesué Junior
 
Rethink programming: a functional approach
Francesco Bruni
 
Introduction to Functional Programming
Francesco Bruni
 
Functional Programming.pptx
KarthickT28
 
Functional programming in python
Edward D. Weinberger
 
Functional programming in python
Edward D. Weinberger
 
Functional programming in Python 1st Edition David Mertz
kimmidalboc0
 
Functional programming in Python 1st Edition David Mertz
nkossivilana87
 
Functional Programming in Python
Haim Michael
 
An Overview Of Python With Functional Programming
Adam Getchell
 
OOPS Object oriented Programming PPT Tutorial
amitnitpatna
 
Thinking in Functions: Functional Programming in Python
Anoop Thomas Mathew
 
Introduction to functional programming
Konrad Szydlo
 
Functional Programming inside OOP? It’s possible with Python
Carlos V.
 
Advanced Programming_Basics of functional Programming.pptx
ManjishPal
 
Functional Programming #FTW
Adriano Bonat
 
Functional programming in Python
Colin Su
 
Why functional programming in C# & F#
Riccardo Terrell
 
Functional programming
ijcd
 
Ad

More from Geison Goes (11)

PDF
Kotlin multiplataforma
Geison Goes
 
PDF
Why companies like Google, Alibaba and UOL choose Flutter
Geison Goes
 
PDF
Functional Swift
Geison Goes
 
PDF
Functional Go
Geison Goes
 
PDF
Functional go
Geison Goes
 
PDF
Restful design principles
Geison Goes
 
PDF
Cucumber - use it to describe user stories and acceptance criterias
Geison Goes
 
PDF
Gil - the responsible to unable paralellism
Geison Goes
 
PDF
An introduction to the ruby ecosystem
Geison Goes
 
PDF
Python Flavors
Geison Goes
 
PDF
Ruby Functional Programming
Geison Goes
 
Kotlin multiplataforma
Geison Goes
 
Why companies like Google, Alibaba and UOL choose Flutter
Geison Goes
 
Functional Swift
Geison Goes
 
Functional Go
Geison Goes
 
Functional go
Geison Goes
 
Restful design principles
Geison Goes
 
Cucumber - use it to describe user stories and acceptance criterias
Geison Goes
 
Gil - the responsible to unable paralellism
Geison Goes
 
An introduction to the ruby ecosystem
Geison Goes
 
Python Flavors
Geison Goes
 
Ruby Functional Programming
Geison Goes
 

Recently uploaded (20)

PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PPTX
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
PDF
Protecting the Digital World Cyber Securit
dnthakkar16
 
PDF
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
PDF
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
PPTX
Services offered by Dynamic Solutions in Pakistan
DaniyaalAdeemShibli1
 
PPTX
oapresentation.pptx
mehatdhavalrajubhai
 
PPTX
TestNG for Java Testing and Automation testing
ssuser0213cb
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Q-Advise
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PPTX
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
PDF
Bandai Playdia The Book - David Glotz
BluePanther6
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
PDF
Solar Panel Installation Guide – Step By Step Process 2025.pdf
CRMLeaf
 
PDF
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
DOCX
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
PDF
How to Seamlessly Integrate Salesforce Data Cloud with Marketing Cloud.pdf
NSIQINFOTECH
 
PDF
The Role of Automation and AI in EHS Management for Data Centers.pdf
TECH EHS Solution
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
Protecting the Digital World Cyber Securit
dnthakkar16
 
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
Services offered by Dynamic Solutions in Pakistan
DaniyaalAdeemShibli1
 
oapresentation.pptx
mehatdhavalrajubhai
 
TestNG for Java Testing and Automation testing
ssuser0213cb
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Q-Advise
 
Presentation about variables and constant.pptx
kr2589474
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
Bandai Playdia The Book - David Glotz
BluePanther6
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
Solar Panel Installation Guide – Step By Step Process 2025.pdf
CRMLeaf
 
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
How to Seamlessly Integrate Salesforce Data Cloud with Marketing Cloud.pdf
NSIQINFOTECH
 
The Role of Automation and AI in EHS Management for Data Centers.pdf
TECH EHS Solution
 

Python functional programming

  • 2. Python Functional Programming Functional Programming by Wikipidia: “Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data". In other words, functional programming promotes code with no side effects, no change of value in variables. It oposes to imperative programming, which enfatizes change of state”.
  • 3. Python Functional Programming What this means? ● No mutable data (no side effect). ● No state (no implicit, hidden state). Once assigned (value binding), a variable (a symbol) does not change its value. All state is bad? No, hidden, implicit state is bad. Functional programming do not eliminate state, it just make it visible and explicit (at least when programmers want it to be). ● Functions are pure functions in the mathematical sense: their output depend only in their inputs, there is not “environment”. ● Same result returned by functions called with the same inputs.
  • 4. Python Functional Programming What are the advantages? ● Cleaner code: "variables" are not modified once defined, so we don't have to follow the change of state to comprehend what a function, a, method, a class, a whole project works. ● Referential transparency: Expressions can be replaced by its values. If we call a function with the same parameters, we know for sure the output will be the same (there is no state anywhere that would change it). There is a reason for which Einstein defined insanity as "doing the same thing over and over again and expecting different results".
  • 5. Python Functional Programming Advantages enabled by referential transparence ● Memoization ○ Cache results for previous function calls. ● Idempotence ○ Same results regardless how many times you call a function. ● Modularization ○ We have no state that pervades the whole code, so we build our project with small, black boxes that we tie together, so it promotes bottom-up programming. ● Ease of debugging ○ Functions are isolated, they only depend on their input and their output, so they are very easy to debug.
  • 6. Python Functional Programming Advantages enabled by referential transparence ● Parallelization ○ Functions calls are independent. ○ We can parallelize in different process/CPUs/computers/… We can execute func1 and func2 in paralell because a won’t be modified. result = func1(a, b) + func2(a, c)
  • 7. Python Functional Programming Advantages enabled by referential transparence ● Concurrence a. With no shared data, concurrence gets a lot simpler: i. No semaphores. ii. No monitors. iii. No locks. iv. No race-conditions. v. No dead-locks.
  • 8. Python Functional Programming Python is a multi paradigm programming language. As a Python programmer why uses functional programming in Python? Python is not a functional language but have a lot of features that enables us to applies functional principles in the development, turning our code more elegant, concise, maintanable, easier to understand and test.
  • 9. Python Functional Programming Don’t Update, Create - String name = 'Geison' name = '{0} Flores'.format(name) FIRSTNAME = 'Geison' LASTNAME = '{0} Flores'.format(FIRSTNAME) NAME = '{0} {1}'.format(FIRSTNAME, LASTNAME)
  • 10. Python Functional Programming Don’t Update, Create - Lists years = [2001, 2002] years.append(2003) years += [2004, 2005] years # [2001, 2002, 2003, 2004, 2005] YEARS = [2001, 2001] ALL_YEARS = YEARS + [2003] + [2004, 2005]
  • 11. Python Functional Programming Don’t Update, Create - Dict ages = {'John': 30} ages['Mary'] = 28 ages # {'John': 30, 'Mary': 28} AGES = {'John': 30} ALL_AGES = dict(AGES.itens() + {'Mary': 28}.itens())
  • 12. Python Functional Programming Higher Order Functions Functions and methods are first-class objects in Python, so if you want to pass a function to another function, you can just treat it as any other object. def caller(f): f() def say_hello(name): return 'Hello {0}'.format(name) caller(say_hello)
  • 13. Python Functional Programming Higher Order Functions - Map map(lambda word: word.upper(), ["milu", "rantanplan"]) # result ["MILU", "RANTANPLAN"] def add_2(n): n + 2 map(add_2, [1, 2, 3]) # result [3, 4, 5]
  • 14. Python Functional Programming Higher Order Functions - Filter filter(lambda word: len(word) == 4, ["milu", "rantanplan"]) # result ["MILU"] def greater_than_10(num): return num > 10 filter(greater_than_10, range(15)) # result [11, 12, 13, 14, 15]
  • 15. Python Functional Programming Higher Order Functions - Reduce import operator reduce(operator.add, [1, 2, 3, 4, 5]) # result 15 def acumullator(a, b): return len(a) + len(b) reduce(acumullator, ["milu", "rantanplan"]) # result 14 reduce(lambda a,b: len(a) + len(b), ["milu", "rantanplan"]) # result 14
  • 16. Python Functional Programming Higher Order Functions - Reduce from itertools import izip list1 = [1, 2, 3] list2 = ["a", "b", "c"] [list(x) for x in izip(list1, list2)] # result [[1, "a"], [2, "b"], [3, "c"]]
  • 17. Python Functional Programming Higher Order Functions - Closure def add_x(x): def adder(y): return x + y return adder add_5 = add_x(5) add_7 = add_x(7) add_5(10) # result 15 add_7(10) # result 17
  • 18. Python Functional Programming Currying and Partial Functions Higher-order functions enable Currying, which the ability to take a function that accepts n parameters and turns it into a composition of n functions each of them take 1 parameter. A direct use of currying is the Partial Functions where if you have a function that accepts n parameters then you can generate from it one of more functions with some parameter values already filled in. from functools import partial plus = lambda a, b: a + b # defining a function that sums 2 numbers plus(3, 5) # result 8 # curring calling partial function by supplying the first parameters with value 1 plus_one = partial(plus, 1) # I can use the new function as normal plus_one(5) # result 6
  • 19. Python Functional Programming Eager vs Lazy Evaluation ● Eager evaluation: expressions are calculated at the moment that variables is assined, function called... ● Lazy evaluation: delays the evaluation of the expression until it is needed. ○ Memory efficient: no memory used to store complete structures. ○ CPU efficient: no need to calculate the complete result before returning. ○ Laziness is not a requisite for FP, but it is a strategy that fits nicely on the paradigm(Haskell). Python uses eager evaluation (but short-circuits && or ||). Python generators are a mechanism for lazy evaluation. Python arrays are not lazy, use enumarators when necessary.
  • 20. Python Functional Programming Recursion Looping by calling a function from within itself. When you don’t have access to mutable data, recursion is used to build up and chain data construction. This is because looping is not a functional concept, as it requires variables to be passed around to store the state of the loop at a given time. ● Purely functional languages have no imperative for-loops, so they use recursion a lot. ● If every recursion created an stack, it would blow up very soon. ● Tail-call optimization (TCO) avoids creating a new stack when the last call in a recursion is the function itself. ● TCO is not implemented in Python. ● Unfortunarely following recursion style in Python has it’s own tax: Performance.
  • 21. Python Functional Programming Solving Python Lack of TCO(Tail Call Optimization) # The functional solution have problens with big values fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2) # The iterative solution using generators works perfectly with large values def fibs(): a = 0 b = 1 while True: yield a a, b = b, a + b
  • 22. Python Functional Programming FP in OOP? It is possible do FP in OOP? Yes it is! ● OOP is orthogonal to FP. ● Well, at least in theory, because: ○ Typical OOP tends to emphasize change of state in objects. ○ Typical OOP mixes the concepts of identity and state. ○ Mixture of data and code raises both conceptual and practical problems. ● OOP functional languages: Scala, F#, ...
  • 23. Python Functional Programming A Pratical Example Exercise: "What's the sum of the first 10 natural number whose square value is divisible by 5?" Imperative: Functional: n, num_elements, s = 1, 0, 0 while num_elements < 10: if n**2 % 5 == 0: s += n num_elements += 1 n += 1 n #275 sum(filter(lambda x: x**2 % 5 == 0, range(1, 100))[:10])
  • 24. Python Functional Programming The last advice Learn at least one functional language, it will open your mind to a new paradigm becoming you a better programmer. Some Functional Languages: ● Haskell ● ML (Standard ML, Objective Caml, ...) ● Scheme ● Erlang ● Scala ● Closure ● F#
  • 25. Python Functional Programming Conclusion ● As you can tell, Python helps you write in functional style but it doesn’t force you to it. ● Writing in functional style enhances your code and makes it more self documented. Actually it will make it more thread-safe also. ● The main support for FP in Python comes from the use of list conprehension, lambdas, closures, iterators and generators, also from the modules functools and itertools. ● Python still lack an important aspect of FP: Pattern Matching and Tails Recursion. ● There should be more work on tail recursion optimization, to encourage developers to use recursion. ● Any other thoughts?
  • 26. Python Functional Programming References ● http://en.wikipedia.org/wiki/Functional_programming ● http://www.cse.chalmers.se/~rjmh/Papers/whyfp.pdf ● http://docs.python.org/2/howto/functional.html ● http://www.youtube.com/watch?v=Ta1bAMOMFOI ● http://clojure.org/ ● http://www.defmacro.org/ramblings/fp.html
  • 27. Python Functional Programming Contact me ● Email: ○ [email protected] ● Skype ○ geisonfgf ● Facebook ○ http://www.facebook.com/geisonfgf ● Twitter ○ http://www.twitter.com/geisonfgf