Scala Bruno Barros e Rebeka Gomes blbs,[email protected].

31
Scala Bruno Barros e Rebeka Gomes blbs,[email protected]

Transcript of Scala Bruno Barros e Rebeka Gomes blbs,[email protected].

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

Scala

Bruno Barros e Rebeka Gomesblbs,[email protected]

Page 2: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Roteiro

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

Page 3: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Introdução

Autor: Martin OderskyCo-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

Page 4: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Introdução

Definição:Linguagem híbrida (funcional/orientada a

objeto) e estaticamente tipadaPode ser interpretada ou compilada em byte-

code.Existe versão para a plataforma Java e

a .NET

Page 5: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Paradigmas

Orientação a objetoTudo é objetoComportamento dos objetos são descritos em

classes e TraitsHerança e overridingGenericity

Page 6: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Paradigmas

FuncionalToda função é um valorPermite usar pattern matchingSuporta funções de alta ordem e anônimasSuporta funções aninhadas e currying

Page 7: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Paradigmasdef 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 <))) }

Page 8: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Especificação

FunçõesToda função é um objeto

É possível: passar funções como parâmetros guardar funções em variáveis retornar funções

Page 9: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

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)

}

}

Page 10: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

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...")

)

}

}

Page 11: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

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)

Page 12: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Especificação

Overriding

class Complex(real: double, imaginary: double) { def re = real

def im = imaginary

override def toString() = "" + re + (if (im < 0) "" else "+")

+ im + "i"

}

Page 13: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Especificação

Herança

class Real (r: double) extends Complex (r,0){override def im = 0;

}

Page 14: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Especificação

Classes abstratas

abstract class IntSet {

def insert(x: int): IntSet

def contains(x: int): boolean

}

Page 15: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Especificação

Trait

trait Printer{

def print(): String

}

trait Set{

def insert(a: Any): Set

def contains(a: Any): boolean

}

Page 16: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Especificação

class EmptyPrintVector() extends Printer with Set {

def print() = “Empty”

def insert(a: Any) = this

def contains(a: Any) = false

}

Page 17: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Especificação

trait Printer{

def print(): String

}

trait EmptySet{

def insert(a: Any) = this

def contains(a: Any) = false

}

Page 18: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Especificação

class EmptyPrintVector() extends Printer with EmptySet {

def print() = “Empty”

}

Page 19: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

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)

}

Page 20: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Especificação

class Date(y: int, m: int, d: int) extends Ord {def year = y

def month = m

def day = d

override def 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)))

}

}

Page 21: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Especificação

Case Classes e pattern matching

abstract class Tree

case class Sum(l: Tree, r: Tree) extends Tree

case class Var(n: String) extends Tree

case class Const(v: int) extends Tree

Page 22: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Especificação

type Environment = String => int

//val env: Environment = { case "x" => 5 case "y" => 7 }

def eval(t: Tree, env: Environment): int = t match {

case Sum(l, r) => eval(l, env) + eval(r, env)

case Var(n) => env(n)

case Const(v) => v

}

Page 23: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Especificação

Genericity

class Reference[T] {

private var contents: T = _

def set(value: T) { contents = value }

def get: T = contents

}

Page 24: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

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))

}

}

Page 25: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Concorrência

Monitores

def synchronized[a] (e: => a): a

def wait()

def wait(msec: long)

def notify()

def notifyAll()

Page 26: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

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

}}

Page 27: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Concorrência

Semaphorespackage scala.concurrentclass Lock {

var available = truedef acquire = synchronized {

while (!available) wait()available = false

}def release = synchronized {

available = truenotify()

}}

Page 28: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Concorrência

SyncVars Futures Parallel Computations Readers/Writers Asynchronous Channels Synchronous Channels Workers Mailboxes Actors

Page 29: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Scala x Java

object HelloWorld { def main(args: Array[String]) { println("Hello, world!") }}

import scala.Predef$;import scala.ScalaObject;

public final class HelloWorld$ implements ScalaObject {

public static final HelloWorld$ MODULE$ = this;

static { new HelloWorld$(); }

public static void main(String args[]) { Predef$.MODULE$.println("Hello, world!"); }

public int $tag() { return scala.ScalaObject.class.$tag(this); }

}

Page 30: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

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

Page 31: Scala Bruno Barros e Rebeka Gomes blbs,rgo2@cin.ufpe.br.

Referências

Scala documentation

http://www.scala-lang.org/docu/index.html