programacao funcional dojo
TRANSCRIPT
B H D o j o
PROGRAMAÇÃO FUNCIONALUma introdução
A METÁFORA DO LENHADOR
2
As linguagens de programação estão se tornando funcionais gradualmente
3
POR QUÊ?Linguaguagens funcionais existem desde sempre. Por que estão se tornando populares somente agora?
4
PRINCÍPIOS BÁSICOS
5
EXPRESSION VS STATEMENT
• Statement(comando) não retorna um valor
• Expression(expressão) retorna um valor e raramente possui side effects
6
Toda linguagem de programação funcional é orientada a expressões
7
PRINCÍPIOS BÁSICOS
• Imutabilidade
• Foco em funções, não em estado
• Funções são valores
• Recourses, não loops
8
IMUTABILIDADE
• Thread Safety
• Sem efeitos colaterais
• Previne referência a null
• Evita acoplamento temporal
• O código se torna mais simples e mais fácil de testar
9
FIZZBUZZ - OO
10
def fizzBuzz(number: Int) = { var result = “"
if (number % 3 == 0 && number % 5 == 0) result = “fizzBuzz" if (number % 3 == 0) result = “fizz" if (number % 5 == 0) result = “buzz" else result }
FIZZBUZZ - FUNCIONAL
11
def fizzBuzz(number:Int) = (number % 3, number % 5) match { case (0, 0) => 'fizzBuzz case (0, _) => 'fizz case (_, 0) => 'buzz case _ => number}
FUNÇÕES DE ALTA ORDEM (HIGH ORDER FUNCTIONS)
São funções que:
• Recebem uma função como parâmetro
• Retorna uma função
Exemplo:
12
def trataErro = { //tratamento de erro...}
def lerArquivo(caminho, tratamentoErro) = { //leitura do arquivo}
lerArquivo("texto.txt", trataErro)
UMA SIMPLES REFATORAÇÃO…De OO para funcional
13
REFATORANDO…
14
def printUpTo(limit: Int): Unit = { var i = 0 while (i <= limit) { println("i = " + i) i += 1 } }
REFATORANDO…
15
def printUpTo(limit: Int): Unit = { for (i <- (0 to limit)) { println("i = " + i) } }}
REFATORANDO…
16
def printUpTo(limit: Int): Unit = { (0 to limit).foreach(println _) }
def printUpTo(limit: Int): Unit = { var i = 0 while (i <= limit) { println("i = " + i) i += 1 } }
def printUpTo(limit: Int): Unit = { (0 to limit).foreach(println) }
Programação funcional se preocupa com "o que fazer" e não em "como fazer"
17
Dúvidas?