SlideShare a Scribd company logo
PROGRAMAÇÃO
FUNCIONAL EM PYTHON
Hugo Tavares
Juarez Bochi
globo.com
THE ELEMENTS OF PROGRAMMING
Primitive Expressions
Means of Combination
Means of Abstraction
PARADIGMAS
Imperativo
Lógico
Orientado a Objetos
Funcional
PYTHON É FUNCIONAL?
FIRST CLASS FUNCTION
HIGHER-ORDER FUNCTION
HIGHER-ORDER FUNCTION - SORT BY
pessoas = [{'nome': 'Adolfo', 'estado': 'MG'},
{'nome': 'Pedro', 'estado': 'RS'},
{'nome': 'Maria', 'estado': 'AC'}]
def por_estado(pessoa1, pessoa2):
return cmp(pessoa1['estado'], pessoa2['estado'])
>>> pprint.pprint(sorted(pessoas, cmp=por_estado))
[{'estado': 'AC', 'nome': 'Maria'},
{'estado': 'MG', 'nome': 'Adolfo'},
{'estado': 'RS', 'nome': 'Pedro'}]
HIGHER-ORDER FUNCTION - DECORATOR
def memoize(fn):
cache = {}
def newfn(arg):
if arg in cache:
return cache[arg]
else:
cache[arg] = fn(arg)
return cache[arg]
return newfn
APLICAÇÃO DECORATOR
def fib(n):
if n in (1, 2):
return 1
return fib(n - 1) + fib(n - 2)
def fast_fib(n):
if n in (1, 2):
return 1
return fast_fib(n - 1) + fast_fib(n - 2)
fast_fib = memoize(fast_fib)
if __name__ == '__main__':
print(timeit.timeit("import fib; fib.fib(35)", number=1))
print(timeit.timeit("import fib; fib.fast_fib(35)", number=1))
# 3.71057915688
# 0.000109195709229
RECURSÃO - MOEDAS
def troco(n, moedas):
if n == 0:
return 1
elif n < 0 or len(moedas) == 0:
return 0
else:
return troco(n, moedas[1:]) + 
troco(n - moedas[0], moedas)
>>> troco(3, [1, 2])
2
>>> troco(100, [50, 7])
1
>>> troco(10, [50, 10, 5, 1, .50, .25, .10, .5, .1])
1153
RECURSÃO - FATORIAL
def fat(n):
if n == 0:
return 1
else:
return n * fat(n - 1)
"""
fat(5)
5 * fat(4)
5 * (4 * fat(3))
5 * (4 * (3 * fat(2)))
5 * (4 * (3 * (2 * fat(1)))
5 * (4 * (3 * (2 * (1 * fat(0)))
5 * (4 * (3 * (2 * (1 * 1))
5 * (4 * (3 * (2 * 1))
5 * (4 * (3 * 2))
5 * (4 * 6)
5 * 24
120
"""
TAIL RECURSION
def fat(n, acc=1):
if n == 0:
return acc
else:
return fat(n - 1, acc * n)
"""
fat(5, 1)
fat(4, 5)
fat(3, 20)
fat(2, 60)
fat(1, 120)
fat(0, 120)
120
"""
>>> fat(1000)
File "", line 5, in fat
...
RuntimeError: maximum recursion depth exceeded
TAIL RECURSION OPTIMIZATION
from optimization import tail_call_optimized
@tail_call_optimized
def fat(n, acc=1):
if n <= 1:
return acc
else:
return fat(n - 1, acc * n)
>>> fat(1000)
402387260077093773543702433923003985719374864210714632543799910429
938512398629020592044208486969404800479988610197196058631666872994
808558901323829669944590997424504087073759918823627727188732519779
505950995276120874975462497043601418278094646496291056393887437886
487337119181045825783647849977012476632889835955735432513185323958
463075557409114262417474349347553428646576611667797396668820291207
379143853719588249808126867838374559731746136085379534524221586593
201928090878297308431392844403281231558611036976801357304216168747
609675871348312025478589320767169132448426236131412508780208000261
683151027341827977704784635868170164365024153691398281264810213092
761244896359928705114964975419909342221566832572080821333186116811
553615836546984046708975602900950537616475847728421889679646244945
160765353408198901385442487984959953319101723355556602139450399736
280750137837615307127761926849034352625200015888535147331611702103
968175921510907788019393178114194545257223865541461062892187960223
@tail_call_optimized
CURRYING
def somador(a):
def soma(b):
return a + b
return soma
>>> somador(1)
<function soma at 0x100499f50>
>>> somador(1)(2)
3
>>> incr = somador(1)
>>> incr(2)
3
>>> incr(3)
4
CURRYING & PARTIALS
def partial(funcao, argumento):
def fn(arg):
return funcao(argumento, arg)
return fn
def to_tag(tag, texto):
return "<{tag}>{texto}</{tag}>".format(tag=tag, texto=texto)
negrito = partial(to_tag, 'b')
italico = partial(to_tag, 'i')
>>> negrito(italico("oi, python brasil"))
"<b><i>oi, python brasil</i></b>"
DATA ABSTRACTION
DATA ABSTRACTION
class Zero(Natural):
def __init__(self):
pass
def __repr__(self):
return "0"
def __add__(self, other):
return other
DATA ABSTRACTION
class Natural(object):
def __init__(self, anterior):
self.anterior = anterior
def __repr__(self):
return repr(self.anterior) + " + 1"
def __add__(self, other):
return self.anterior + other.sucessor()
def sucessor(self):
return Natural(anterior=self)
DATA ABSTRACTION
>>> zero = Zero()
>>> um = zero.sucessor()
>>> dois = um.sucessor()
>>> um
0 + 1
>>> dois
0 + 1 + 1
>>> um + dois
0 + 1 + 1 + 1
STOP WRITING CLASSES
Jack Diederich, PyCon US 2012
http://pyvideo.org/video/880/stop-writing-classes
STOP WRITING CLASSES
class Greeting(object):
def __init__(self, greeting="hello"):
self.greeting = greeting
def greet(self, name):
return "{greet}! {name}".format(greet=self.greeting, name)
>>> hola = Greeting("hola")
>>> hola.greet("bob")
"hola! bob"
LAZYNESS & GENERATORS
LAZYNESS & GENERATORS
def naturais():
i = 0
while True:
yield i
i += 1
def pares():
return ifilter(lambda x: x % 2 == 0, naturais())
>>> sum(take(pares(), 10))
90
RESUMO
Código compreensível
Fácil de testar
Fácil de manter
Fácil de escalar
REFERÊNCIAS
Structure and Interpretation of Computer Programs
Functional Programming Principles in Scala
Stop Writing Classes" - PyCon US 2012
Códigos usados na palestra:
OBRIGADO!
@hltbra
@jbochi

More Related Content

What's hot

Regression and Classification with R
Regression and Classification with RRegression and Classification with R
Regression and Classification with R
Yanchang Zhao
 
Closures
ClosuresClosures
Closures
SV.CO
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentation
Martin McBride
 
{tidytext}と{RMeCab}によるモダンな日本語テキスト分析
{tidytext}と{RMeCab}によるモダンな日本語テキスト分析{tidytext}と{RMeCab}によるモダンな日本語テキスト分析
{tidytext}と{RMeCab}によるモダンな日本語テキスト分析
Takashi Kitano
 
The Chain Rule, Part 2
The Chain Rule, Part 2The Chain Rule, Part 2
The Chain Rule, Part 2
Pablo Antuna
 
Codigos
CodigosCodigos
Codigos
Brian Joseff
 
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver){tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
Takashi Kitano
 
Analytics functions in mysql, oracle and hive
Analytics functions in mysql, oracle and hiveAnalytics functions in mysql, oracle and hive
Analytics functions in mysql, oracle and hive
Ankit Beohar
 
하스켈 프로그래밍 입문 4
하스켈 프로그래밍 입문 4하스켈 프로그래밍 입문 4
하스켈 프로그래밍 입문 4
Kwang Yul Seo
 
Ampersand method
Ampersand methodAmpersand method
Ampersand method
Andrew Grimm
 
Simple swing programs
Simple swing programsSimple swing programs
Simple swing programs
vishal choudhary
 
하스켈 프로그래밍 입문 3
하스켈 프로그래밍 입문 3하스켈 프로그래밍 입문 3
하스켈 프로그래밍 입문 3
Kwang Yul Seo
 
{:from => 'Java', :to => 'Ruby'}
{:from => 'Java', :to => 'Ruby'}{:from => 'Java', :to => 'Ruby'}
{:from => 'Java', :to => 'Ruby'}
Shintaro Kakutani
 
Elixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicitElixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicit
Tobias Pfeiffer
 
The Chain Rule, Part 1
The Chain Rule, Part 1The Chain Rule, Part 1
The Chain Rule, Part 1
Pablo Antuna
 
{tidygraph}と{ggraph}によるモダンなネットワーク分析
{tidygraph}と{ggraph}によるモダンなネットワーク分析{tidygraph}と{ggraph}によるモダンなネットワーク分析
{tidygraph}と{ggraph}によるモダンなネットワーク分析
Takashi Kitano
 
Elixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicitElixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicit
Tobias Pfeiffer
 
Dwi putri erlinda saraswati
Dwi putri erlinda saraswatiDwi putri erlinda saraswati
Dwi putri erlinda saraswati
Dwi Putri Erlinda Saraswati
 
Data Analytics Project_Eun Seuk Choi (Eric)
Data Analytics Project_Eun Seuk Choi (Eric)Data Analytics Project_Eun Seuk Choi (Eric)
Data Analytics Project_Eun Seuk Choi (Eric)Eric Choi
 
The Moore-Spiegel Oscillator
The Moore-Spiegel OscillatorThe Moore-Spiegel Oscillator
The Moore-Spiegel Oscillator
Abhranil Das
 

What's hot (20)

Regression and Classification with R
Regression and Classification with RRegression and Classification with R
Regression and Classification with R
 
Closures
ClosuresClosures
Closures
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentation
 
{tidytext}と{RMeCab}によるモダンな日本語テキスト分析
{tidytext}と{RMeCab}によるモダンな日本語テキスト分析{tidytext}と{RMeCab}によるモダンな日本語テキスト分析
{tidytext}と{RMeCab}によるモダンな日本語テキスト分析
 
The Chain Rule, Part 2
The Chain Rule, Part 2The Chain Rule, Part 2
The Chain Rule, Part 2
 
Codigos
CodigosCodigos
Codigos
 
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver){tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
 
Analytics functions in mysql, oracle and hive
Analytics functions in mysql, oracle and hiveAnalytics functions in mysql, oracle and hive
Analytics functions in mysql, oracle and hive
 
하스켈 프로그래밍 입문 4
하스켈 프로그래밍 입문 4하스켈 프로그래밍 입문 4
하스켈 프로그래밍 입문 4
 
Ampersand method
Ampersand methodAmpersand method
Ampersand method
 
Simple swing programs
Simple swing programsSimple swing programs
Simple swing programs
 
하스켈 프로그래밍 입문 3
하스켈 프로그래밍 입문 3하스켈 프로그래밍 입문 3
하스켈 프로그래밍 입문 3
 
{:from => 'Java', :to => 'Ruby'}
{:from => 'Java', :to => 'Ruby'}{:from => 'Java', :to => 'Ruby'}
{:from => 'Java', :to => 'Ruby'}
 
Elixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicitElixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicit
 
The Chain Rule, Part 1
The Chain Rule, Part 1The Chain Rule, Part 1
The Chain Rule, Part 1
 
{tidygraph}と{ggraph}によるモダンなネットワーク分析
{tidygraph}と{ggraph}によるモダンなネットワーク分析{tidygraph}と{ggraph}によるモダンなネットワーク分析
{tidygraph}と{ggraph}によるモダンなネットワーク分析
 
Elixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicitElixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicit
 
Dwi putri erlinda saraswati
Dwi putri erlinda saraswatiDwi putri erlinda saraswati
Dwi putri erlinda saraswati
 
Data Analytics Project_Eun Seuk Choi (Eric)
Data Analytics Project_Eun Seuk Choi (Eric)Data Analytics Project_Eun Seuk Choi (Eric)
Data Analytics Project_Eun Seuk Choi (Eric)
 
The Moore-Spiegel Oscillator
The Moore-Spiegel OscillatorThe Moore-Spiegel Oscillator
The Moore-Spiegel Oscillator
 

Similar to Programação funcional em Python

Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
Arturo Herrero
 
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Dr. Volkan OBAN
 
Advanced python
Advanced pythonAdvanced python
Advanced pythonEU Edge
 
Secretary_Game_With_Rejection.pdf
Secretary_Game_With_Rejection.pdfSecretary_Game_With_Rejection.pdf
Secretary_Game_With_Rejection.pdf
AlexRoberts205071
 
R code for data manipulation
R code for data manipulationR code for data manipulation
R code for data manipulation
Avjinder (Avi) Kaler
 
R code for data manipulation
R code for data manipulationR code for data manipulation
R code for data manipulation
Avjinder (Avi) Kaler
 
Introduction to R
Introduction to RIntroduction to R
Introduction to R
Sander Kieft
 
funwithalgorithms.pptx
funwithalgorithms.pptxfunwithalgorithms.pptx
funwithalgorithms.pptx
Tess Ferrandez
 
R is a very flexible and powerful programming language, as well as a.pdf
R is a very flexible and powerful programming language, as well as a.pdfR is a very flexible and powerful programming language, as well as a.pdf
R is a very flexible and powerful programming language, as well as a.pdf
annikasarees
 
BUilt in Functions and Simple programs in R.pdf
BUilt in Functions and Simple programs in R.pdfBUilt in Functions and Simple programs in R.pdf
BUilt in Functions and Simple programs in R.pdf
karthikaparthasarath
 
Python 1 liners
Python 1 linersPython 1 liners
Python 1 liners
Nattawut Phetmak
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
Calvin Cheng
 
Algorithm Design and Analysis - Practical File
Algorithm Design and Analysis - Practical FileAlgorithm Design and Analysis - Practical File
Algorithm Design and Analysis - Practical File
KushagraChadha1
 
Recursion in C
Recursion in CRecursion in C
Recursion in C
Lakshmi Sarvani Videla
 
Practicle 1.docx
Practicle 1.docxPracticle 1.docx
Practicle 1.docx
GaneshPawar819187
 
The Ring programming language version 1.10 book - Part 40 of 212
The Ring programming language version 1.10 book - Part 40 of 212The Ring programming language version 1.10 book - Part 40 of 212
The Ring programming language version 1.10 book - Part 40 of 212
Mahmoud Samir Fayed
 
Solucionario de Ejercicios de PL/SQL.pdf
Solucionario de Ejercicios de PL/SQL.pdfSolucionario de Ejercicios de PL/SQL.pdf
Solucionario de Ejercicios de PL/SQL.pdf
Pedro Narváez
 
R/Finance 2009 Chicago
R/Finance 2009 ChicagoR/Finance 2009 Chicago
R/Finance 2009 Chicago
gyollin
 

Similar to Programação funcional em Python (20)

Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
 
Advanced python
Advanced pythonAdvanced python
Advanced python
 
Secretary_Game_With_Rejection.pdf
Secretary_Game_With_Rejection.pdfSecretary_Game_With_Rejection.pdf
Secretary_Game_With_Rejection.pdf
 
R code for data manipulation
R code for data manipulationR code for data manipulation
R code for data manipulation
 
R code for data manipulation
R code for data manipulationR code for data manipulation
R code for data manipulation
 
Vcs9
Vcs9Vcs9
Vcs9
 
Introduction to R
Introduction to RIntroduction to R
Introduction to R
 
funwithalgorithms.pptx
funwithalgorithms.pptxfunwithalgorithms.pptx
funwithalgorithms.pptx
 
R is a very flexible and powerful programming language, as well as a.pdf
R is a very flexible and powerful programming language, as well as a.pdfR is a very flexible and powerful programming language, as well as a.pdf
R is a very flexible and powerful programming language, as well as a.pdf
 
BUilt in Functions and Simple programs in R.pdf
BUilt in Functions and Simple programs in R.pdfBUilt in Functions and Simple programs in R.pdf
BUilt in Functions and Simple programs in R.pdf
 
Python 1 liners
Python 1 linersPython 1 liners
Python 1 liners
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
 
Algorithm Design and Analysis - Practical File
Algorithm Design and Analysis - Practical FileAlgorithm Design and Analysis - Practical File
Algorithm Design and Analysis - Practical File
 
R meets Hadoop
R meets HadoopR meets Hadoop
R meets Hadoop
 
Recursion in C
Recursion in CRecursion in C
Recursion in C
 
Practicle 1.docx
Practicle 1.docxPracticle 1.docx
Practicle 1.docx
 
The Ring programming language version 1.10 book - Part 40 of 212
The Ring programming language version 1.10 book - Part 40 of 212The Ring programming language version 1.10 book - Part 40 of 212
The Ring programming language version 1.10 book - Part 40 of 212
 
Solucionario de Ejercicios de PL/SQL.pdf
Solucionario de Ejercicios de PL/SQL.pdfSolucionario de Ejercicios de PL/SQL.pdf
Solucionario de Ejercicios de PL/SQL.pdf
 
R/Finance 2009 Chicago
R/Finance 2009 ChicagoR/Finance 2009 Chicago
R/Finance 2009 Chicago
 

Recently uploaded

FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 

Programação funcional em Python

  • 1. PROGRAMAÇÃO FUNCIONAL EM PYTHON Hugo Tavares Juarez Bochi globo.com
  • 2. THE ELEMENTS OF PROGRAMMING Primitive Expressions Means of Combination Means of Abstraction
  • 6. HIGHER-ORDER FUNCTION - SORT BY pessoas = [{'nome': 'Adolfo', 'estado': 'MG'}, {'nome': 'Pedro', 'estado': 'RS'}, {'nome': 'Maria', 'estado': 'AC'}] def por_estado(pessoa1, pessoa2): return cmp(pessoa1['estado'], pessoa2['estado']) >>> pprint.pprint(sorted(pessoas, cmp=por_estado)) [{'estado': 'AC', 'nome': 'Maria'}, {'estado': 'MG', 'nome': 'Adolfo'}, {'estado': 'RS', 'nome': 'Pedro'}]
  • 7. HIGHER-ORDER FUNCTION - DECORATOR def memoize(fn): cache = {} def newfn(arg): if arg in cache: return cache[arg] else: cache[arg] = fn(arg) return cache[arg] return newfn
  • 8. APLICAÇÃO DECORATOR def fib(n): if n in (1, 2): return 1 return fib(n - 1) + fib(n - 2) def fast_fib(n): if n in (1, 2): return 1 return fast_fib(n - 1) + fast_fib(n - 2) fast_fib = memoize(fast_fib) if __name__ == '__main__': print(timeit.timeit("import fib; fib.fib(35)", number=1)) print(timeit.timeit("import fib; fib.fast_fib(35)", number=1)) # 3.71057915688 # 0.000109195709229
  • 9.
  • 10. RECURSÃO - MOEDAS def troco(n, moedas): if n == 0: return 1 elif n < 0 or len(moedas) == 0: return 0 else: return troco(n, moedas[1:]) + troco(n - moedas[0], moedas) >>> troco(3, [1, 2]) 2 >>> troco(100, [50, 7]) 1 >>> troco(10, [50, 10, 5, 1, .50, .25, .10, .5, .1]) 1153
  • 11. RECURSÃO - FATORIAL def fat(n): if n == 0: return 1 else: return n * fat(n - 1) """ fat(5) 5 * fat(4) 5 * (4 * fat(3)) 5 * (4 * (3 * fat(2))) 5 * (4 * (3 * (2 * fat(1))) 5 * (4 * (3 * (2 * (1 * fat(0))) 5 * (4 * (3 * (2 * (1 * 1)) 5 * (4 * (3 * (2 * 1)) 5 * (4 * (3 * 2)) 5 * (4 * 6) 5 * 24 120 """
  • 12. TAIL RECURSION def fat(n, acc=1): if n == 0: return acc else: return fat(n - 1, acc * n) """ fat(5, 1) fat(4, 5) fat(3, 20) fat(2, 60) fat(1, 120) fat(0, 120) 120 """ >>> fat(1000) File "", line 5, in fat ... RuntimeError: maximum recursion depth exceeded
  • 13. TAIL RECURSION OPTIMIZATION from optimization import tail_call_optimized @tail_call_optimized def fat(n, acc=1): if n <= 1: return acc else: return fat(n - 1, acc * n) >>> fat(1000) 402387260077093773543702433923003985719374864210714632543799910429 938512398629020592044208486969404800479988610197196058631666872994 808558901323829669944590997424504087073759918823627727188732519779 505950995276120874975462497043601418278094646496291056393887437886 487337119181045825783647849977012476632889835955735432513185323958 463075557409114262417474349347553428646576611667797396668820291207 379143853719588249808126867838374559731746136085379534524221586593 201928090878297308431392844403281231558611036976801357304216168747 609675871348312025478589320767169132448426236131412508780208000261 683151027341827977704784635868170164365024153691398281264810213092 761244896359928705114964975419909342221566832572080821333186116811 553615836546984046708975602900950537616475847728421889679646244945 160765353408198901385442487984959953319101723355556602139450399736 280750137837615307127761926849034352625200015888535147331611702103 968175921510907788019393178114194545257223865541461062892187960223
  • 15. CURRYING def somador(a): def soma(b): return a + b return soma >>> somador(1) <function soma at 0x100499f50> >>> somador(1)(2) 3 >>> incr = somador(1) >>> incr(2) 3 >>> incr(3) 4
  • 16. CURRYING & PARTIALS def partial(funcao, argumento): def fn(arg): return funcao(argumento, arg) return fn def to_tag(tag, texto): return "<{tag}>{texto}</{tag}>".format(tag=tag, texto=texto) negrito = partial(to_tag, 'b') italico = partial(to_tag, 'i') >>> negrito(italico("oi, python brasil")) "<b><i>oi, python brasil</i></b>"
  • 18. DATA ABSTRACTION class Zero(Natural): def __init__(self): pass def __repr__(self): return "0" def __add__(self, other): return other
  • 19. DATA ABSTRACTION class Natural(object): def __init__(self, anterior): self.anterior = anterior def __repr__(self): return repr(self.anterior) + " + 1" def __add__(self, other): return self.anterior + other.sucessor() def sucessor(self): return Natural(anterior=self)
  • 20. DATA ABSTRACTION >>> zero = Zero() >>> um = zero.sucessor() >>> dois = um.sucessor() >>> um 0 + 1 >>> dois 0 + 1 + 1 >>> um + dois 0 + 1 + 1 + 1
  • 21. STOP WRITING CLASSES Jack Diederich, PyCon US 2012 http://pyvideo.org/video/880/stop-writing-classes
  • 22. STOP WRITING CLASSES class Greeting(object): def __init__(self, greeting="hello"): self.greeting = greeting def greet(self, name): return "{greet}! {name}".format(greet=self.greeting, name) >>> hola = Greeting("hola") >>> hola.greet("bob") "hola! bob"
  • 24. LAZYNESS & GENERATORS def naturais(): i = 0 while True: yield i i += 1 def pares(): return ifilter(lambda x: x % 2 == 0, naturais()) >>> sum(take(pares(), 10)) 90
  • 25. RESUMO Código compreensível Fácil de testar Fácil de manter Fácil de escalar
  • 26. REFERÊNCIAS Structure and Interpretation of Computer Programs Functional Programming Principles in Scala Stop Writing Classes" - PyCon US 2012 Códigos usados na palestra: