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

What's hot (20)

Identifiers
Identifiers Identifiers
Identifiers
Then Murugeshwari
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
Fundamentals of Programming Constructs.pptx
Fundamentals of  Programming Constructs.pptxFundamentals of  Programming Constructs.pptx
Fundamentals of Programming Constructs.pptx
vijayapraba1
 
Linked list
Linked listLinked list
Linked list
Trupti Agrawal
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
Sets in python
Sets in pythonSets in python
Sets in python
baabtra.com - No. 1 supplier of quality freshers
 
Heap sort
Heap sortHeap sort
Heap sort
Mohd Arif
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
narmadhakin
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
Abhilash Nair
 
Algorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms IAlgorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms I
Mohamed Loey
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Threaded Binary Tree
Threaded Binary TreeThreaded Binary Tree
Threaded Binary Tree
khabbab_h
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Kumar Gaurav
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
P3 InfoTech Solutions Pvt. Ltd.
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
Kamal Acharya
 
c++ lab manual
c++ lab manualc++ lab manual
c++ lab manual
Shrunkhala Wankhede
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notations
Nikhil Sharma
 
Bubble sort
Bubble sortBubble sort
Bubble sort
Manek Ar
 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
deepalishinkar1
 

Similar to Python functional programming (20)

Functional python
Functional pythonFunctional python
Functional python
Jesué Junior
 
Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approach
Francesco Bruni
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Francesco Bruni
 
Functional Programming.pptx
Functional Programming.pptxFunctional Programming.pptx
Functional Programming.pptx
KarthickT28
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
Edward D. Weinberger
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
Edward D. Weinberger
 
Functional programming in Python 1st Edition David Mertz
Functional programming in Python 1st Edition David MertzFunctional programming in Python 1st Edition David Mertz
Functional programming in Python 1st Edition David Mertz
kimmidalboc0
 
Functional programming in Python 1st Edition David Mertz
Functional programming in Python 1st Edition David MertzFunctional programming in Python 1st Edition David Mertz
Functional programming in Python 1st Edition David Mertz
nkossivilana87
 
Functional Programming in Python
Functional Programming in PythonFunctional Programming in Python
Functional Programming in Python
Haim Michael
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
Adam Getchell
 
OOPS Object oriented Programming PPT Tutorial
OOPS Object oriented Programming PPT TutorialOOPS Object oriented Programming PPT Tutorial
OOPS Object oriented Programming PPT Tutorial
amitnitpatna
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
Anoop Thomas Mathew
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
Konrad Szydlo
 
Functional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonFunctional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with Python
Carlos V.
 
Functional Programming #FTW
Functional Programming #FTWFunctional Programming #FTW
Functional Programming #FTW
Adriano Bonat
 
Seminar fp
Seminar fpSeminar fp
Seminar fp
VeerapatBoonvanich1
 
Functional programming in Python
Functional programming in PythonFunctional programming in Python
Functional programming in Python
Colin Su
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
Riccardo Terrell
 
Functional programming
Functional programmingFunctional programming
Functional programming
ijcd
 
Functional programming
Functional programmingFunctional programming
Functional programming
Prashant Kalkar
 
Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approach
Francesco Bruni
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Francesco Bruni
 
Functional Programming.pptx
Functional Programming.pptxFunctional Programming.pptx
Functional Programming.pptx
KarthickT28
 
Functional programming in Python 1st Edition David Mertz
Functional programming in Python 1st Edition David MertzFunctional programming in Python 1st Edition David Mertz
Functional programming in Python 1st Edition David Mertz
kimmidalboc0
 
Functional programming in Python 1st Edition David Mertz
Functional programming in Python 1st Edition David MertzFunctional programming in Python 1st Edition David Mertz
Functional programming in Python 1st Edition David Mertz
nkossivilana87
 
Functional Programming in Python
Functional Programming in PythonFunctional Programming in Python
Functional Programming in Python
Haim Michael
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
Adam Getchell
 
OOPS Object oriented Programming PPT Tutorial
OOPS Object oriented Programming PPT TutorialOOPS Object oriented Programming PPT Tutorial
OOPS Object oriented Programming PPT Tutorial
amitnitpatna
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
Anoop Thomas Mathew
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
Konrad Szydlo
 
Functional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonFunctional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with Python
Carlos V.
 
Functional Programming #FTW
Functional Programming #FTWFunctional Programming #FTW
Functional Programming #FTW
Adriano Bonat
 
Functional programming in Python
Functional programming in PythonFunctional programming in Python
Functional programming in Python
Colin Su
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
Riccardo Terrell
 
Functional programming
Functional programmingFunctional programming
Functional programming
ijcd
 
Ad

More from Geison Goes (11)

Kotlin multiplataforma
Kotlin multiplataformaKotlin multiplataforma
Kotlin multiplataforma
Geison Goes
 
Why companies like Google, Alibaba and UOL choose Flutter
Why companies like Google, Alibaba and UOL choose FlutterWhy companies like Google, Alibaba and UOL choose Flutter
Why companies like Google, Alibaba and UOL choose Flutter
Geison Goes
 
Functional Swift
Functional SwiftFunctional Swift
Functional Swift
Geison Goes
 
Functional Go
Functional GoFunctional Go
Functional Go
Geison Goes
 
Functional go
Functional goFunctional go
Functional go
Geison Goes
 
Restful design principles
Restful design principlesRestful design principles
Restful design principles
Geison Goes
 
Cucumber - use it to describe user stories and acceptance criterias
Cucumber - use it to describe user stories and acceptance criteriasCucumber - use it to describe user stories and acceptance criterias
Cucumber - use it to describe user stories and acceptance criterias
Geison Goes
 
Gil - the responsible to unable paralellism
Gil - the responsible to unable paralellismGil - the responsible to unable paralellism
Gil - the responsible to unable paralellism
Geison Goes
 
An introduction to the ruby ecosystem
An introduction to the ruby ecosystemAn introduction to the ruby ecosystem
An introduction to the ruby ecosystem
Geison Goes
 
Python Flavors
Python FlavorsPython Flavors
Python Flavors
Geison Goes
 
Ruby Functional Programming
Ruby Functional ProgrammingRuby Functional Programming
Ruby Functional Programming
Geison Goes
 
Kotlin multiplataforma
Kotlin multiplataformaKotlin multiplataforma
Kotlin multiplataforma
Geison Goes
 
Why companies like Google, Alibaba and UOL choose Flutter
Why companies like Google, Alibaba and UOL choose FlutterWhy companies like Google, Alibaba and UOL choose Flutter
Why companies like Google, Alibaba and UOL choose Flutter
Geison Goes
 
Functional Swift
Functional SwiftFunctional Swift
Functional Swift
Geison Goes
 
Restful design principles
Restful design principlesRestful design principles
Restful design principles
Geison Goes
 
Cucumber - use it to describe user stories and acceptance criterias
Cucumber - use it to describe user stories and acceptance criteriasCucumber - use it to describe user stories and acceptance criterias
Cucumber - use it to describe user stories and acceptance criterias
Geison Goes
 
Gil - the responsible to unable paralellism
Gil - the responsible to unable paralellismGil - the responsible to unable paralellism
Gil - the responsible to unable paralellism
Geison Goes
 
An introduction to the ruby ecosystem
An introduction to the ruby ecosystemAn introduction to the ruby ecosystem
An introduction to the ruby ecosystem
Geison Goes
 
Ruby Functional Programming
Ruby Functional ProgrammingRuby Functional Programming
Ruby Functional Programming
Geison Goes
 
Ad

Recently uploaded (20)

Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
Eliminate the complexities of Event-Driven Architecture with Domain-Driven De...
Eliminate the complexities of Event-Driven Architecture with Domain-Driven De...Eliminate the complexities of Event-Driven Architecture with Domain-Driven De...
Eliminate the complexities of Event-Driven Architecture with Domain-Driven De...
SheenBrisals
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-OffMicro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Tier1 app
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!
PhilMeredith3
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Rebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core FoundationRebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core Foundation
Cadabra Studio
 
How to purchase, license and subscribe to Microsoft Azure_PDF.pdf
How to purchase, license and subscribe to Microsoft Azure_PDF.pdfHow to purchase, license and subscribe to Microsoft Azure_PDF.pdf
How to purchase, license and subscribe to Microsoft Azure_PDF.pdf
victordsane
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Prachi Desai
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
Eliminate the complexities of Event-Driven Architecture with Domain-Driven De...
Eliminate the complexities of Event-Driven Architecture with Domain-Driven De...Eliminate the complexities of Event-Driven Architecture with Domain-Driven De...
Eliminate the complexities of Event-Driven Architecture with Domain-Driven De...
SheenBrisals
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-OffMicro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Tier1 app
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!
PhilMeredith3
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Rebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core FoundationRebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core Foundation
Cadabra Studio
 
How to purchase, license and subscribe to Microsoft Azure_PDF.pdf
How to purchase, license and subscribe to Microsoft Azure_PDF.pdfHow to purchase, license and subscribe to Microsoft Azure_PDF.pdf
How to purchase, license and subscribe to Microsoft Azure_PDF.pdf
victordsane
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Prachi Desai
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 

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