1 / 31

Scala

Scala. Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br. Roteiro. Introdução Paradigmas Especificação Concorrência Scala x Java Exercícios. Introdução. Autor: Martin Odersky Co-designer do generics de Java e implementou o javac

terah
Download Presentation

Scala

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br

  2. Roteiro Introdução Paradigmas Especificação Concorrência Scala x Java Exercícios

  3. Introdução • Autor: Martin Odersky • Co-designer do generics de Java e implementou o javac • Criada em 2001 na École Polytechnique Fédérale de Lausanne (EPFL) • Primeira versão disponibilizada em 2003 • A versão mais recente é de Maio de 2008

  4. Introdução • Definição: • Linguagem híbrida (funcional/orientada a objeto) e estaticamente tipada • Pode ser interpretada ou compilada em byte-code. • Existe versão para a plataforma Java e a .NET

  5. Paradigmas • Orientação a objeto • Tudo é objeto • Comportamento dos objetos são descritos em classes e Traits • Herança e overriding • Genericity

  6. Paradigmas • Funcional • Toda função é um valor • Permite usar pattern matching • Suporta funções de alta ordem e anônimas • Suporta funções aninhadas e currying

  7. Paradigmas def sort(xs: Array[int]) { def swap(i: int, j: int) { val t = xs(i); xs(i) = xs(j); xs(j) = t } def sort1(l: int, r: int) { val pivot = xs((l + r) / 2) var i = l; var j = r while (i <= j) { while (xs(i) < pivot) { i = i + 1 } while (xs(j) > pivot) { j = j - 1 } if (i <= j) { swap(i, j) i = i + 1 j = j - 1 } } if (l < j) sort1(l, j) if (j < r) sort1(i, r) } sort1(0, xs.length 1) } def sort(xs: Array[int]): Array[int] = if (xs.length <= 1) xs else { val pivot = xs(xs.length / 2) Array.concat( sort(xs filter (pivot >)), xs filter (pivot ==), sort(xs filter (pivot <))) }

  8. Especificação • Funções • Toda função é um objeto • É possível: • passar funções como parâmetros • guardar funções em variáveis • retornar funções

  9. Especificação object Timer { def oncePerSecond(callback: () => unit) { while (true) { callback(); Thread sleep 1000 } } def timeFlies() { println("time flies like an arrow...") } def main(args: Array[String]) { oncePerSecond(timeFlies) } }

  10. Especificação • Funções anônimas object TimerAnonymous { def oncePerSecond(callback: () => unit) { while (true) { callback(); Thread sleep 1000 } } def main(args: Array[String]) { oncePerSecond(() => println("time flies like an arrow...") ) } }

  11. Especificação • Classes • Declaração: class Complex(real: double, imaginary: double) { def re() = real def im() = imaginary } • Criando uma instância new Complex(1.5, 2.3)

  12. Especificação • Overriding class Complex(real: double, imaginary: double) { def re = real def im = imaginary overridedef toString() = "" + re + (if (im < 0) "" else "+") + im + "i" }

  13. Especificação • Herança class Real (r: double) extends Complex (r,0){ overridedef im = 0; }

  14. Especificação • Classes abstratas abstractclass IntSet { def insert(x: int): IntSet def contains(x: int): boolean }

  15. Especificação • Trait trait Printer{ def print(): String } trait Set{ def insert(a: Any): Set def contains(a: Any): boolean }

  16. Especificação class EmptyPrintVector() extends Printer with Set { def print() = “Empty” def insert(a: Any) = this def contains(a: Any) = false }

  17. Especificação trait Printer{ def print(): String } trait EmptySet{ def insert(a: Any) = this def contains(a: Any) = false }

  18. Especificação class EmptyPrintVector() extends Printer with EmptySet { def print() = “Empty” }

  19. Especificação • Mixins trait Ord { def < (that: Any): boolean def <=(that: Any): boolean = (this < that) || (this == that) def > (that: Any): boolean = !(this <= that) def >=(that: Any): boolean = !(this < that) }

  20. Especificação class Date(y: int, m: int, d: int) extends Ord { def year = y def month = m def day = d overridedef equals(that: Any): boolean = that.isInstanceOf[Date] && { val o = that.asInstanceOf[Date] o.day == day && o.month == month && o.year == year } def <(that: Any): boolean = { if (!that.isInstanceOf[Date]) error("cannot compare " + that + " and a Date") val o = that.asInstanceOf[Date] (year < o.year) || (year == o.year && (month < o.month || (month == o.month && day < o.day))) } }

  21. Especificação Case Classes e pattern matching abstractclass Tree caseclass Sum(l: Tree, r: Tree) extends Tree caseclass Var(n: String) extends Tree caseclass Const(v: int) extends Tree

  22. Especificação typeEnvironment = String => int //valenv: Environment = { case "x" => 5 case "y" => 7 } defeval(t: Tree, env: Environment): int = t match { caseSum(l, r) => eval(l, env) + eval(r, env) case Var(n) => env(n) caseConst(v) => v }

  23. Especificação • Genericity class Reference[T] { privatevar contents: T = _ def set(value: T) { contents = value } def get: T = contents }

  24. Especificação object IntegerReference { def main(args: Array[String]) { val cell = new Reference[Int] cell.set(13) println("Reference contains the half of " + (cell.get * 2)) } }

  25. Concorrência • Monitores def synchronized[a] (e: => a): a def wait() def wait(msec: long) def notify() def notifyAll()

  26. Concorrência class BoundedBuffer[a] (N: int) { var in = 0, out = 0, n = 0 val elems = new Array[a](N) def put(x: a) = synchronized { while (n >= N) wait() elems(in) = x ; in = (in + 1) % N ; n = n + 1 if (n == 1) notifyAll() } def get: a = synchronized { while (n == 0) wait() val x = elems(out) ; out = (out + 1) % N ; n = n 1 if (n == N 1) notifyAll() x } }

  27. Concorrência • Semaphores packagescala.concurrent classLock { varavailable = true defacquire = synchronized { while (!available) wait() available = false } def release = synchronized { available = true notify() } }

  28. Concorrência SyncVars Futures ParallelComputations Readers/Writers AsynchronousChannels SynchronousChannels Workers Mailboxes Actors

  29. Scala x Java importscala.Predef$; importscala.ScalaObject; publicfinal classHelloWorld$ implementsScalaObject { publicstatic final HelloWorld$ MODULE$ = this; static{ newHelloWorld$(); } publicstaticvoidmain(String args[]) { Predef$.MODULE$.println("Hello, world!"); } publicint$tag() { returnscala.ScalaObject.class.$tag(this); } } object HelloWorld { def main(args: Array[String]) { println("Hello, world!") } }

  30. Exercícios 1 - Defina as seguintes funções square e sumSquare em Scala; 2 - Como ficaria o seguinte código Haskell em Scala? fibonnaci :: Num a => a -> a fibonnaci 0 = 1 fibonnaci 1 = 1 fibonnaci n = fibonnaci (n - 1) + fibonnaci (n - 2) 3 - Explique brevemente alguns tipos de abstrações utilizadas para obter concorrência em Scala

  31. Referências • Scala documentation http://www.scala-lang.org/docu/index.html

More Related