henrique seabra, rilter tavares {hsd,rtn}@cin.ufpe.br f#

Click here to load reader

Upload: internet

Post on 18-Apr-2015

225 views

Category:

Documents


3 download

TRANSCRIPT

  • Slide 1
  • Henrique Seabra, Rilter Tavares {hsd,rtn}@cin.ufpe.br F#
  • Slide 2
  • Roteiro A linguagem Origem Caractersticas Aplicaes Configurando o ambiente Sintaxe Referncias
  • Slide 3
  • A Linguagem - Origem F# uma linguagem de programao funcional tipada para o Framewok.NET Teve origem na famlia ML de linguagens ML uma linguagem de programao funcional de proposta geral desenvolvida no final dos anos 1970 na Universidade de Edimburgo, e considerada uma linguagem funcional impura, por permitir a programao imperativa, ao contrrio de outras linguagens funcionais como Haskell. visto como uma implementao de ML para.NET
  • Slide 4
  • A Linguagem - Caractersticas F# foi projetado desde o incio para dar uma boa interoperabilidade com outras linguagens.NET uma linguagem de programao de script/ functional/ imperativa/ orientada a objeto Possui boa performance, cdigo sucinto, suporta generics e pode ser compilado por outros compiladores, como o de Ocaml No limitada ao Windows
  • Slide 5
  • F#: Combinando Paradigmas Functional Strong TypingSuccinctType Inference Data Types and Patterns 1 st Class FunctionsMeta-Programming Objects.NET OO ModelInteroperable.NET Visual StudioLibrariesToolsConcurrencyLINQ Tools F# CompilerF# Interactive Visual Studio Integration
  • Slide 6
  • A Linguagem - Aplicaes Aplicaes de processamento pesado Sistemas de datamining Mercados Financeiros Anlise estatstica Jogos para XBOX usando XNA
  • Slide 7
  • Configurando o Ambiente Baixar a ltima verso disponibilizada (F# CTP release) no link: http://research.microsoft.com/fsharp/release.aspxhttp://research.microsoft.com/fsharp/release.aspx Descompactar o arquivo Executar o arquivo InstallFSharp.msi
  • Slide 8
  • Hello World Criar arquivo hello.fs No prompt de comando do Windows, executar a seguinte instruo: c:Arquivos de programas\FSharp-1.9.6.2\bin\fsc.exe hello.fs #light printfn "Hello World"
  • Slide 9
  • F# em 2 minutos
  • Slide 10
  • Inferncia de tipos let square x = x * x;; let concat (x : string) y = x + y;; concat "Hello, " "World!";;
  • Slide 11
  • Funes de primeira ordem Lambda expression >List.map (fun x -> x % 2 = 0) [1.. 10];;
  • Slide 12 printfn "%d * %f = %s" 5 0.75 ((5.0 * 0.75).ToString());; 5 * 0.750000 = 3.75 %d, %f, e %s so, respectivamente, inteiros, floats e strings">
  • Printfn > printfn "%d * %f = %s" 5 0.75 ((5.0 * 0.75).ToString());; 5 * 0.750000 = 3.75 %d, %f, e %s so, respectivamente, inteiros, floats e strings
  • Slide 13
  • Listas let vowels = ['e'; 'i'; 'o'; 'u'];; let cons = 'a' :: vowels;; let sometimes = vowels @ ['y'];;
  • Slide 14 printfn "Has element %d" i) ">
  • Listas Iter Percorre cada item da coleo Idntico ao foreach Ex: Imprime todos os itens de uma lista List.iter (fun i -> printfn "Has element %d" i) [1.. 10]
  • Slide 15
  • Listas Map Transforma uma coleo baseada numa funo Ex: Mapeia um array de inteiros para strings Array.map (fun (i : int) -> i.ToString()) [| 1.. 10 |]
  • Slide 16
  • Listas Fold Transforma ou reduz a coleo em um nico valor Como iter e map, tambm aplicado a cada elemento nica que possui um parmetro acumulativo Ex: Somatrio de cada item da srie (reduzir a srie a um nico valor Parmetro acumulador o somatrio de todos os elementos Seq.fold (fun acc i -> i + acc) 0 { 1.. 10 }
  • Slide 17
  • Sequences System.Collections.Generic.IEnumerator ou Seq Podem especificar sries infinitas Apenas valor atual guardado na memria Exemplo de seqncia de todos os inteiros: let allIntegers = Seq.init_infinite (fun i -> i)
  • Slide 18 let getNumberInfo (x : int) = (x, x.ToString(), x * x);; val getNumberInf"> let getNumberInfo (x : int) = (x, x.ToString(), x * x);; val getNumberInfo : int -> int * string * int > getNumberInfo 42;; val it : int * string * int = (42, "42", 1764) > let printBlogInfo (owner, title, url) = printfn "%s's blog [%s] is online at '%s'" owner title url;; val printBlogInfo : string * string * string -> unit > let myBlog = (Pessoa", Nome do blog", "http://blog.com");; val myBlog : string * string * string > printBlogInfo myBlog;; Pessoa's blog [Nome do blog] is online at 'http://blog.com val it : unit = ()"> let getNumberInfo (x : int) = (x, x.ToString(), x * x);; val getNumberInf" title="Tuplas > let tupla = (1, false, "texto");; val tuple : int * bool * string > let getNumberInfo (x : int) = (x, x.ToString(), x * x);; val getNumberInf">
  • Tuplas > let tupla = (1, false, "texto");; val tuple : int * bool * string > let getNumberInfo (x : int) = (x, x.ToString(), x * x);; val getNumberInfo : int -> int * string * int > getNumberInfo 42;; val it : int * string * int = (42, "42", 1764) > let printBlogInfo (owner, title, url) = printfn "%s's blog [%s] is online at '%s'" owner title url;; val printBlogInfo : string * string * string -> unit > let myBlog = (Pessoa", Nome do blog", "http://blog.com");; val myBlog : string * string * string > printBlogInfo myBlog;; Pessoa's blog [Nome do blog] is online at 'http://blog.com val it : unit = ()
  • Slide 19
  • Records type Address = {Name:string; Address:string; Zip:int} let whiteHouse = {Name="The White House"; Address="1600 Pennsylvania Avenue"; Zip=20500}
  • Slide 20
  • Option Values Dificuldade de achar o valor null Valores sempre inicializados Necessidade de ausncia de valores Similar aos valores nulos de C# Option type representa dois estados: Some e None type Person = { First : string; MI : string option; Last : string } let billg = {First = "Bill"; MI = Some("H"); Last = "Gates" } let chrsmith = {First = "Chris"; MI = None; Last = "Smith" }
  • Slide 21
  • Function Currying > let addThree x y z = x + y + z;; val addThree : int -> int -> int -> int > let addTwo x y = addThree 10 x y;; val addTwo : int -> int -> int > addTwo 1 1;; val it : int = 12
  • Slide 22 printfn "Hello, Steve" | Worker(name) | Lead(name, _) -> printfn "Hello, %s" name">
  • Discriminated Union type MicrosoftEmployee = | BillGates | SteveBalmer | Worker of string | Lead of string * MicrosoftEmployee list let printGreeting (emp : MicrosoftEmployee) = match emp with | BillGates -> printfn "Hello, Bill" | SteveBalmer -> printfn "Hello, Steve" | Worker(name) | Lead(name, _) -> printfn "Hello, %s" name
  • Slide 23
  • Discriminated Union type MicrosoftEmployee = | BillGates | SteveBalmer | Worker of string | Lead of string * MicrosoftEmployee list | ChrisSmith
  • Slide 24 "x is a string" | :? int -> "x is an int" | :? Exception -> "x is an exception""> 0 | a :: [] -> 1 | a :: b :: [] -> 2 | a :: b :: c :: [] -> 3 | _ -> failwith "List i">
  • Pattern Matching let listLength alist = match alist with | [] -> 0 | a :: [] -> 1 | a :: b :: [] -> 2 | a :: b :: c :: [] -> 3 | _ -> failwith "List is too big!" let getType (x : obj) = match x with | :? string -> "x is a string" | :? int -> "x is an int" | :? Exception -> "x is an exception"
  • Slide 25 "4201" let result = rev (toStr (double 512)) let result = 512 |> double |> toStr |> rev">
  • let (|>) x f = f x 'a -> ('a -> 'b) -> 'b Operador Pipe let double x = x + x let toStr (x : int) = x.ToString() let rev (x : string) = new String(Array.rev (x.ToCharArray())) // 512 -> 1024 -> "1024" -> "4201" let result = rev (toStr (double 512)) let result = 512 |> double |> toStr |> rev
  • Slide 26 let listOfX = [x; x; x];; val listOfX : L"> let listOfX = [x; x; x];; val listOfX : Lazy list > x.Force();; Computed. val it : int = 42"> let listOfX = [x; x; x];; val listOfX : L" title="Lazy Values Apenas computado quando necessrio Ex: > let x = lazy (printfn "Computed."; 42);; val x : Lazy > let listOfX = [x; x; x];; val listOfX : L">
  • Lazy Values Apenas computado quando necessrio Ex: > let x = lazy (printfn "Computed."; 42);; val x : Lazy > let listOfX = [x; x; x];; val listOfX : Lazy list > x.Force();; Computed. val it : int = 42
  • Slide 27
  • Lazy Values Pode ser usado para evitar computaes desnecessrias ou caras til na construo de valores recursivos Ex: circularList referencia ele mesmo (loop infinito de ListNodes com valor 1) Sem Lazy Initialization, esse tipo de valor seria impossvel Compilador faz esse trabalho nos bastidores type InfiniteList = | ListNode of int * InfiniteList let rec circularList = ListNode(1, circularList)
  • Slide 28
  • Mais alguns exemplos
  • Slide 29
  • Exerccio 1 Construa uma funo que recebe um Inteiro e retorna um Booleano que indica se o referido nmero primo ou no. Ex: ehPrimo 3 = true ehPrimo 1 = false Faa uma funo que, dado um Inteiro, retorna uma lista com todos os nmeros primos menores ou iguais a ele. Ex: primosAte 5 = [2,3,5] ou [5,3,2]
  • Slide 30
  • Exerccio 2 Faa uma funo que retorne o elemento da folha mais esquerda de uma rvore. Ex: leftmost arv Faa uma funo que retorne, da esquerda para direita, todos os elementos de uma rvore. Ex: elementos arv
  • Slide 31
  • Referncias Microsoft Research. Disponvel em: http://research.microsoft.com/fsharp/manual/lexyacc.aspx. ltimo acesso em: 14/05/2008 http://research.microsoft.com/fsharp/manual/lexyacc.aspx SMITH, Chris. MSDN Blogs. Disponvel em: http://blogs.msdn.com/chrsmith/archive/2008/05/02/f-in-20-minutes-part-i.aspx. ltimo acesso em: 14/05/2008 http://blogs.msdn.com/chrsmith/archive/2008/05/02/f-in-20-minutes-part-i.aspx SEMPLE,Thomas Alexander. iMasters. Disponvel em: http://imasters.uol.com.br/artigo/7750/dotnet/conheca_o_f. ltimo acesso em: 14/05/2008 http://imasters.uol.com.br/artigo/7750/dotnet/conheca_o_f Wikipedia. Disponvel em: http://pt.wikipedia.org/wiki/ML_(linguagem_de_programa%C3%A7%C3%A3o). ltimo acesso em: 14/05/2008 http://pt.wikipedia.org/wiki/ML_(linguagem_de_programa%C3%A7%C3%A3o) Microsoft Research. Disponvel em: http://www.microsoft.com/france/vision/mstechdays08/WebcastMSDN.aspx?EID=1 2841bd9-158e-4dc3-bc5b-8e3d5fd7b552. ltimo acesso em: 14/05/2008 http://www.microsoft.com/france/vision/mstechdays08/WebcastMSDN.aspx?EID=1 2841bd9-158e-4dc3-bc5b-8e3d5fd7b552 PICKERING, Robert. Foundations of F#. Apress: 2007. 360 p.
  • Slide 32
  • Henrique Seabra, Rilter Tavares {hsd,rtn}@cin.ufpe.br F#