introdução ao f# michel pavan macedo [email protected]
TRANSCRIPT
![Page 2: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/2.jpg)
O que é o F#?• Linguagem .NET
– É possível usar qualquer biblioteca .NET do F#– É possível usar qualquer biblioteca F# de outras linguagens
para .NET
• Combina dois paradigmas de programação importantes– Programação Orientada a Objeto– Programação Funcional– Também muito útil para script
![Page 3: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/3.jpg)
Por que F#?• Programação funcional é o foco da linguagem
• Que linguagens utilizaremos em um futuro próximo?– Algumas características do F# poderão ser incorporadas em
outras linguagens e bibliotecas
• Desenvolvida pela Microsoft Research– Bem testada e otimizada– Comunidade crescente
• Graças ao .NET pode ser utilizada como parte de um projeto maior
![Page 4: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/4.jpg)
Agenda• F# #light• F# funcional• F# orientado a objetos• F# interativo• F# real
![Page 5: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/5.jpg)
Sintaxe• Estaticamente tipado (como o Java e C#, não como Ruby,
Python e JavaScript)– Tipos são inferidos pelo contexto
– Usa tipos parametrizados quando possível
// valor inteiro (int)let n = 42
// valor do tipo texto (string)let str = "Hello world!"
// Função (int -> int)let add10(n) = n + 10
// Função identidade ('a -> 'a)let id(sth) = sth
![Page 6: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/6.jpg)
Valores• É possível representar 0, 1 ou mais valores
• Algum valor ou nenhum valor
// valor do tipo unit (unit)let nada = ()
// valor inteiro (int)let numero = (5)
// tupla de inteiro e string (int * String)let tupla = (5, “Cinco”)
// um valor Int32 e um valor Stringlet valor, nome = tupla
// Função de tipo “int -> int option”let positivo n = if n > 0 then Some(n) else None
![Page 7: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/7.jpg)
Funções• Toda função tem um parâmetro e um retorno
// recebe unit, retorna unit: unit -> unitlet imprime5() = printf “%s é igual a %d” “cinco” 5
// recebe inteiro, retorna inteiro: int -> intlet maisUm(n) = n + 1
// recebe inteiro, retorna inteiro: int -> intlet maisDois n = n + 2
// recebe tupla de inteiros (int * int) -> intlet soma(a, b) = a + b
// recebe tupla de inteiros int -> int -> intlet potencia a b = a ** b
![Page 8: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/8.jpg)
Discriminated Union• Discriminated union em F#
type Option<'T> = | None | Some of 'T
type List<'T> = | Nil | Cons of 'T * List<'T>
Option<'T>Option<'T>
Option<'T>.SomeOption<'T>.Some
valor: 'Tvalor: 'T
Option<'T>.NoneOption<'T>.None
![Page 9: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/9.jpg)
DEMOInterativo
![Page 10: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/10.jpg)
Agenda• F# #light• F# funcional• F# orientado a objetos• F# interativo• F# real
![Page 11: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/11.jpg)
Funcional vs Imperativo• Abordagem imperativa
– Atribuição é a operação mais importante
• Abordagem funcional– Baseado em recursividade– Todas as estruturas são imutáveis por padrão– Funções funcionais puras não tem efeitos colaterais• Fácil de testar e depurar• Fácil de paralelizar
![Page 12: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/12.jpg)
Funcional vs Imperativo• Em F# você pode combinar ambas abordagens
– Imperativo é bom para interoperabilidade com .NET
• Funcional
• Imperativo
// Fatorial (funcional)let rec fat_f n = if (n = 0) then 1 else n * fat_f(n – 1)
// Fatorial (imperativo)let fat_i n = let mutable ret = 1 for i = 1 to n do ret <- ret * i done ret
![Page 13: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/13.jpg)
Imutabilidade• Além de unidades e records
open System
// declara unidades de medida[<Measure>] type copinho[<Measure>] type litro[<Measure>] type dia// declara constante de conversãolet copinhoPorLitro : float<copinho/litro> = 6.0<copinho/litro>// declara função de conversãolet emLitros (c:float<copinho>) = c / copinhoPorLitro
// declara um recordtype Programador = { Nome: String; Cafe: float<litro/dia> }// instancia um programadorlet euDoPassado = { Nome = “Michel”; Cafe = 1.5<litro/dia> }// tenta alterar o programador, mas ele é imutáveleuDoPassado.Cafe <- (emLitros 6<copinho>) / 1.0<dia>// instancia um novo programadorlet eu = { euDoPassado with Cafe = emLitros(6<copinho>)/1.0<dia> }
![Page 14: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/14.jpg)
DEMOTutorial Introdutório
![Page 15: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/15.jpg)
Agenda• F# #light• F# funcional• F# orientado a objetos• F# interativo• F# real
![Page 16: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/16.jpg)
De Amanda Laucher e Josh Graham• Problema: encontrar a passagem mais barata para uma
determinada viagem// direçãotype direction = |To |From |Return
// classe da passagemtype ticketClass = |Standard |First
// passagemtype ticket = {Price:decimal; Class:ticketClass; Direction:direction}
![Page 17: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/17.jpg)
continuação
type Journey (tickets) =
let lowestPrice cls dir = (tickets |> List.filter(fun x -> x.Class = cls && x.Direction = dir) |> List.min).Price
let getCheapestList cls dir = tickets |> List.filter (fun x -> x.Class = cls && x.Direction = dir && x.Price = (lowestPrice cls dir))
let getTicketsByClass cls = tickets |> List.filter (fun x -> x.Class = cls)
let getTicketsByDirection dir = tickets |> List.filter (fun x -> x.Direction = dir)
![Page 18: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/18.jpg)
continuação
member x.CheapestStdTo = getCheapestList Standard To member x.CheapestFirstTo = getCheapestList First To member x.CheapestStdFrom = getCheapestList Standard From member x.CheapestFirstFrom = getCheapestList First From member x.CheapestStdReturn = getCheapestList Standard Return member x.CheapestFirstReturn = getCheapestList First Return member x.StandardCheapestBoth = if ((lowestPrice First To) + (lowestPrice First From)) > (lowestPrice First Return) then x.CheapestFirstReturn else x.CheapestFirstFrom @ x.CheapestFirstTo member x.AllOutwardTickets = getTicketsByDirection To member x.AllInwardTickets = getTicketsByDirection From member x.AllReturnTickets = getTicketsByDirection Return member x.AllStandardTickets = getTicketsByClass Standard member x.AllFirstTickets = getTicketsByClass First
![Page 19: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/19.jpg)
Agenda• F# #light• F# funcional• F# orientado a objetos• F# interativo• F# real
![Page 20: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/20.jpg)
F# interativo• Três motivos porque eu amo Shell
– Consiste apenas de um core de operadores– Esses poucos operadores são para trabalhar com pipes– É fácil e prático de testar
• O que faz uma linguagem de script?– O código deve ser o mais conciso possível– Normalmente são interpretadas (F# é compilado)– F# tem verificação estática
![Page 21: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/21.jpg)
DEMOVisualização 3D
![Page 22: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/22.jpg)
Agenda• F# #light• F# funcional• F# orientado a objetos• F# interativo• F# real
![Page 23: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/23.jpg)
De um slide de Don SymeI’ve been coding in F# lately, for a production task.
F# allows you to move smoothly in your programming style... I start with pure functional code, shift slightly towards an objected-oriented style, and in production code, I sometimes have to do some imperative programming.
I can start with a pure idea, and still finish my project with realistic code. You’re never disappointed in any phase of the project!
Julien Laugel, Chief Software Architect, www.eurostocks.com
![Page 24: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/24.jpg)
DEMOASP.NET MVC WebForms (C#)
Razor (C#)
![Page 25: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/25.jpg)
Referências• HubFS (comunidade de F#)http://cs.hubfs.net/
• InfoQ (tem ótimas palestras de F#)http://www.infoq.com/
• Try F#http://www.tryfsharp.org/
• Exemplos de F# (aqueles dessa apresentação)http://fsharpsamples.codeplex.com/
![Page 26: Introdução ao F# Michel Pavan Macedo michelpm@gmail.com](https://reader035.vdocuments.pub/reader035/viewer/2022062418/552fc120497959413d8cb644/html5/thumbnails/26.jpg)
Referências• Bastantes tutoriais de recursos do F#
http://leibnizdream.wordpress.com/
• Ótimo blog de F# (inclusive slides base para essa apresentação)http://www.tomasP.net/
• Ótimo livro de F#http://www.amazon.com/Real-World-Functional-Programming-Examples/dp/1933988924