SlideShare a Scribd company logo
Programação Funcional
FISL 2013
Juarez Bochi
λ
Sunday, July 14, 13
Juarez Bochi
Sunday, July 14, 13
Juarez Bochi
Sunday, July 14, 13
Juarez Bochi
Sunday, July 14, 13
Juarez Bochi
Sunday, July 14, 13
Juarez Bochi
Sunday, July 14, 13
Agenda
• Motivação
• Conceitos
• Exemplos
• Resumo
Sunday, July 14, 13
Motivação
Sunday, July 14, 13
Ler um arquivo, listar
as palavras mais
comuns em ordem
decrescente.
Sunday, July 14, 13
Ler um arquivo, listar
as palavras mais
comuns em ordem
decrescente.
Sunday, July 14, 13
Donald Knuth
X
Sunday, July 14, 13
Donald Knuth Doug McIlroy
X
Sunday, July 14, 13
Donald Knuth Doug McIlroy
X
10+ páginas de Pascal/WEB
Sunday, July 14, 13
Donald Knuth Doug McIlroy
X
10+ páginas de Pascal/WEB 6 linhas de shell
Sunday, July 14, 13
tr -cs A-Za-z 'n' |
tr A-Z a-z |
sort |
uniq -c |
sort -rn |
sed ${1}q
Sunday, July 14, 13
Sunday, July 14, 13
$ cat discurso.txt | tr -cs A-Za-z 'n' | tr A-Z a-z | sort |
uniq -c | sort -rn | sed 40q
65 e
48 de
42 a
35 o
32 que
18 os
15 para
15 com
14 mais
13 nao
13 do
11 as
10 um
10 dos
10 da
9 das
8 ela
7 todos
7 se
7 pais
7 muito
6 ruas
6 brasil
5 violencia
Sunday, July 14, 13
“Keep it simple, make
it general, and make it
intelligible.”
Doug McIlroy
Sunday, July 14, 13
“Keep it simple, make
it general, and make it
intelligible.”
Doug McIlroy
Sunday, July 14, 13
Conceitos
Sunday, July 14, 13
Paradigmas
• Imperativo
• Lógico
• Funcional
• Orientado a Objetos
Sunday, July 14, 13
Paradigma Imperativo
Linguagem Computador
Variáveis Mutáveis Endereço de memória
Estruturas de controle
(if-then-else, loop)
Jumps
Sunday, July 14, 13
“Can Programming Be
Liberated from the von.
Neumann Style?”
John Backus - Turing Award Lecture
Sunday, July 14, 13
Programação Funcional
• Concentrar em teorias, não mutações
• Minimizar mudança de estados
• Sem estruturas de controle
imperativas
• Foco em funções
Sunday, July 14, 13
“Programação Funcional
é ortogonal à Orientação
a Objetos”
Sunday, July 14, 13
Elementos de Programação
• Expressões Primitivas
• Meios de Combinação
• Meios de Abstração
Sunday, July 14, 13
Exemplos
Sunday, July 14, 13
First Class Functions
Sunday, July 14, 13
First Class Functions
Sunday, July 14, 13
Closure
> var inc, dec;
undefined
> function contador() {
... var x = 0;
... inc = function() { return ++x; };
... dec = function() { return --x; };
... }
undefined
> contador();
undefined
Sunday, July 14, 13
Closure
> inc();
1
> inc();
2
> dec();
1
> dec();
0
> inc();
1
> x
ReferenceError: x is not defined
Sunday, July 14, 13
> import Control.Applicative
> let foo = fmap (+3) (+2)
> foo 10
15
Sunday, July 14, 13
> import Control.Applicative
> let foo = fmap (+3) (+2)
> foo 10
15
Sunday, July 14, 13
> (defn soma3 [x] (+ x 3))
Sunday, July 14, 13
> (defn soma3 [x] (+ x 3))
> (map soma3 [2 4 6])
(5 7 9)
Sunday, July 14, 13
> (defn soma3 [x] (+ x 3))
> (map soma3 [2 4 6])
(5 7 9)
Sunday, July 14, 13
> (defn soma3 [x] (+ x 3))
> (map soma3 [2 4 6])
(5 7 9)
> (pmap soma3 [2 4 6])
(5 7 9)
Sunday, July 14, 13
Higher Order Function
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'}]
Sunday, July 14, 13
Recursão
Sunday, July 14, 13
Recursão
(define (fib n)
.. (if (< n 2)
.. n
.. (+ (fib (- n 1)) (fib (- n 2)))))
(fib 10)
=> 55
Sunday, July 14, 13
Tail Call Optimization
1. fib(5)
2. fib(4) + fib(3)
3. (fib(3) + fib(2)) + (fib(2) + fib(1))
4. ((fib(2) + fib(1)) + (fib(1) + fib(0))) + ((fibb(1) + fib(0)) + fib(1))
5. (((fib(1) + fib(0)) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) + fib(0)) +
fib(1))
Sunday, July 14, 13
Tail Call Optimization
(define (fib n)
.. (letrec ((fib-aux (lambda (n a b)
.. (if (= n 0)
.. a
.. (fib-aux (- n 1) b (+ a b))))))
.. (fib-aux n 0 1)))
(fib 1000)
=> 4.346655768693743e+208
1. fib(5)
2. fib(4) + fib(3)
3. (fib(3) + fib(2)) + (fib(2) + fib(1))
4. ((fib(2) + fib(1)) + (fib(1) + fib(0))) + ((fibb(1) + fib(0)) + fib(1))
5. (((fib(1) + fib(0)) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) + fib(0)) +
fib(1))
Sunday, July 14, 13
Sunday, July 14, 13
Currying & Partials
def to_tag(tag, texto):
return "<{tag}>{texto}</{tag}>".format(tag=tag,
texto=texto)
Sunday, July 14, 13
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)
Sunday, July 14, 13
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')
Sunday, July 14, 13
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, FISL!"))
"<b><i>Oi FISL!</i></b>"
Sunday, July 14, 13
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)
DSL!!
negrito = partial(to_tag, 'b')
italico = partial(to_tag, 'i')
>>> negrito(italico("Oi, FISL!"))
"<b><i>Oi FISL!</i></b>"
Sunday, July 14, 13
Laziness
Sunday, July 14, 13
Laziness
Sunday, July 14, 13
Laziness
def from(n: Int): Stream[Int] = n #:: from(n+1)
Sunday, July 14, 13
Laziness
def from(n: Int): Stream[Int] = n #:: from(n+1)
 
Sunday, July 14, 13
Laziness
def from(n: Int): Stream[Int] = n #:: from(n+1)
 
val nats = from(0)
Sunday, July 14, 13
Laziness
def from(n: Int): Stream[Int] = n #:: from(n+1)
 
val nats = from(0)
 
Sunday, July 14, 13
Laziness
def from(n: Int): Stream[Int] = n #:: from(n+1)
 
val nats = from(0)
 
def sieve(s: Stream[Int]): Stream[Int] =
Sunday, July 14, 13
Laziness
def from(n: Int): Stream[Int] = n #:: from(n+1)
 
val nats = from(0)
 
def sieve(s: Stream[Int]): Stream[Int] =
s.head #:: sieve(s.tail filter (_ % s.head != 0))
Sunday, July 14, 13
Laziness
def from(n: Int): Stream[Int] = n #:: from(n+1)
 
val nats = from(0)
 
def sieve(s: Stream[Int]): Stream[Int] =
s.head #:: sieve(s.tail filter (_ % s.head != 0))
 
Sunday, July 14, 13
Laziness
def from(n: Int): Stream[Int] = n #:: from(n+1)
 
val nats = from(0)
 
def sieve(s: Stream[Int]): Stream[Int] =
s.head #:: sieve(s.tail filter (_ % s.head != 0))
 
val primes = sieve(from(2))
Sunday, July 14, 13
Laziness
def from(n: Int): Stream[Int] = n #:: from(n+1)
 
val nats = from(0)
 
def sieve(s: Stream[Int]): Stream[Int] =
s.head #:: sieve(s.tail filter (_ % s.head != 0))
 
val primes = sieve(from(2))
 
Sunday, July 14, 13
Laziness
def from(n: Int): Stream[Int] = n #:: from(n+1)
 
val nats = from(0)
 
def sieve(s: Stream[Int]): Stream[Int] =
s.head #:: sieve(s.tail filter (_ % s.head != 0))
 
val primes = sieve(from(2))
 
(primes take N).toList
Sunday, July 14, 13
Data Abstraction
class Zero(Natural):
def __init__(self):
pass
def __repr__(self):
return "0"
def __add__(self, other):
return other
Sunday, July 14, 13
Data Abstraction
class Zero(Natural):
def __init__(self):
pass
def __repr__(self):
return "0"
def __add__(self, other):
return other
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)
Sunday, July 14, 13
Data Abstraction
class Zero(Natural):
def __init__(self):
pass
def __repr__(self):
return "0"
def __add__(self, other):
return other
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)>>> zero = Zero()
>>> um = zero.sucessor()
>>> dois = um.sucessor()
>>> um
0 + 1
>>> dois
0 + 1 + 1
>>> um + dois
0 + 1 + 1 + 1
Sunday, July 14, 13
Resumo
Sunday, July 14, 13
Blub Paradox
Sunday, July 14, 13
Resumo
Código fácil de entender
Sunday, July 14, 13
Resumo
Código fácil de manter
Sunday, July 14, 13
Resumo
Código fácil de testar
Sunday, July 14, 13
Resumo
Código fácil de escalar
Sunday, July 14, 13
Obrigado!
@jbochi
Sunday, July 14, 13
Referências
• http://www.leancrew.com/all-this/2011/12/more-shell-less-egg/
• http://onesixtythree.com/literate/literate2.pdf
• http://mitpress.mit.edu/sicp/
• http://www.paulgraham.com/avg.html
• https://www.coursera.org/course/progfun
• http://www.slideshare.net/jbochi/programao-funcional-em-python
• https://raw.github.com/richhickey/slides/master/simplicitymatters.pdf
• http://pragprog.com/magazines/2013-01/functional-programming-basics
• http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html
• http://en.literateprograms.org/Fibonacci_numbers_(Scheme)
• http://norvig.com/21-days.html
• http://www.youtube.com/watch?v=3jg1AheF4n0
• http://www.flickr.com/photos/niceric/74977685/sizes/l/in/
Sunday, July 14, 13

More Related Content

PDF
Introduction to Groovy
PDF
轻量级文本工具集
PDF
From Ruby to Haskell (Kansai Yami RubyKaigi)
PDF
CoffeeScript
PDF
穏やかにファイルを削除する
PDF
Top 10 php classic traps
PDF
The ABCs of OTP
PDF
Clustering com numpy e cython
Introduction to Groovy
轻量级文本工具集
From Ruby to Haskell (Kansai Yami RubyKaigi)
CoffeeScript
穏やかにファイルを削除する
Top 10 php classic traps
The ABCs of OTP
Clustering com numpy e cython

What's hot (20)

PDF
Functional Pattern Matching on Python
PDF
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
PDF
หัดเขียน A.I. แบบ AlphaGo กันชิวๆ
PPTX
Build a compiler in 2hrs - NCrafts Paris 2015
PDF
How old consoles work!
PDF
Frege is a Haskell for the JVM
PPTX
Perl6 a whistle stop tour
PDF
Perl6 a whistle stop tour
KEY
Learning How To Use Jquery #5
PDF
Intro to OTP in Elixir
PDF
Begin with Python
PPTX
PDF
The amazing world behind your ORM
PPTX
Chap 5 php files part-2
PDF
A Python Crash Course
PDF
Investigating Python Wats
PDF
Having Fun Programming!
PDF
RではじめるTwitter解析
PDF
Don't do this
PDF
Damn Fine CoffeeScript
Functional Pattern Matching on Python
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
หัดเขียน A.I. แบบ AlphaGo กันชิวๆ
Build a compiler in 2hrs - NCrafts Paris 2015
How old consoles work!
Frege is a Haskell for the JVM
Perl6 a whistle stop tour
Perl6 a whistle stop tour
Learning How To Use Jquery #5
Intro to OTP in Elixir
Begin with Python
The amazing world behind your ORM
Chap 5 php files part-2
A Python Crash Course
Investigating Python Wats
Having Fun Programming!
RではじめるTwitter解析
Don't do this
Damn Fine CoffeeScript
Ad

Similar to Programação Funcional (20)

PDF
Clojure night
PPTX
First Ride on Rust
PDF
Programación funcional con haskell
ODP
Python quickstart for programmers: Python Kung Fu
PDF
D-Talk: What's awesome about Ruby 2.x and Rails 4
KEY
関数潮流(Function Tendency)
PDF
Purely Functional I/O
PDF
Seattle.rb 6.4
PDF
Fluentdがよくわからなかった話
PDF
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
PDF
Python utan-stodhjul-motorsag
PDF
Crash course to learn python programming
PDF
python...............................................
PDF
Music as data
PDF
Dig1108 Lesson 3
PPTX
Functional linear data structures in f#
PDF
FP in scalaで鍛える関数型脳
PDF
PythonOOP
PPTX
class.4.pptxgxdfggdxfgxfgdxbhnjgnjmjmbxg
PDF
An Introduction to JavaScript: Week 4
Clojure night
First Ride on Rust
Programación funcional con haskell
Python quickstart for programmers: Python Kung Fu
D-Talk: What's awesome about Ruby 2.x and Rails 4
関数潮流(Function Tendency)
Purely Functional I/O
Seattle.rb 6.4
Fluentdがよくわからなかった話
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Python utan-stodhjul-motorsag
Crash course to learn python programming
python...............................................
Music as data
Dig1108 Lesson 3
Functional linear data structures in f#
FP in scalaで鍛える関数型脳
PythonOOP
class.4.pptxgxdfggdxfgxfgdxbhnjgnjmjmbxg
An Introduction to JavaScript: Week 4
Ad

Recently uploaded (20)

PPTX
Final SEM Unit 1 for mit wpu at pune .pptx
PDF
Getting started with AI Agents and Multi-Agent Systems
PDF
STKI Israel Market Study 2025 version august
PPTX
Chapter 5: Probability Theory and Statistics
PPTX
observCloud-Native Containerability and monitoring.pptx
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PPTX
Modernising the Digital Integration Hub
PPTX
Tartificialntelligence_presentation.pptx
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PPTX
The various Industrial Revolutions .pptx
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
Hindi spoken digit analysis for native and non-native speakers
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
Hybrid model detection and classification of lung cancer
Final SEM Unit 1 for mit wpu at pune .pptx
Getting started with AI Agents and Multi-Agent Systems
STKI Israel Market Study 2025 version august
Chapter 5: Probability Theory and Statistics
observCloud-Native Containerability and monitoring.pptx
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
DP Operators-handbook-extract for the Mautical Institute
Univ-Connecticut-ChatGPT-Presentaion.pdf
Modernising the Digital Integration Hub
Tartificialntelligence_presentation.pptx
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Group 1 Presentation -Planning and Decision Making .pptx
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
The various Industrial Revolutions .pptx
Assigned Numbers - 2025 - Bluetooth® Document
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
cloud_computing_Infrastucture_as_cloud_p
Hindi spoken digit analysis for native and non-native speakers
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
Hybrid model detection and classification of lung cancer

Programação Funcional