Tipos e métodos genéricos, Tuplas e funções como objetos
Quiz yourself by thinking what should be in
each of the black spaces below before clicking
on it to display the answer.
Help!
|
|
||||
---|---|---|---|---|---|
Classes em Scala podem ser tipos como parâmetros. | abstract class IntStack {
def push(x: Int): IntStack = new IntNonEmptyStack(x, this)
def isEmpty: Boolean
def top: Int
def pop: IntStack
}
🗑
|
||||
Usando classes genéricas. | val x = new EmptyStack[Int]
val y = x.push(1).push(2)
println(y.pop.top)
🗑
|
||||
Generalizar classes genéricas. | Como exemplo a classe IntSet:
abstract class Set[A] {
def incl(x: A): Set[A]
def contains(x: A): Boolean
}
🗑
|
||||
Função para retornar o quociente inteiro e o resto de dois argumentos inteiros. | def divmod(x: Int, y: Int) = new Tuple2[Int, Int](x / y, x % y)
🗑
|
||||
O programa é funcional. | def prime(x : Int) : Boolean = 2.to(x-1).filter(x % _ == 0).isEmpty
println(prime(1))
println(prime(5))
println(prime(9))
println(prime(11))
🗑
|
||||
Listas criadas e manipuladas. | var arr = for(i <- 0 to 20 if i % 2 == 0) yield i
arr.foreach(println)
🗑
|
||||
Em Scala, funções também são objetos, possibilitando passar funções como argumentos e outras funcionalidades. | object Timer {
def oncePerSecond(callback: () => unit) {
while (true) { callback(); Thread sleep 1000 }
}
def timeFlies() {
println("o tempo corre como um raio...")
}
def main(args: Array[String]) {
oncePerSecond(timeFlies)
}
}
🗑
|
||||
Uma função pode ser definida apenas para ser passada como parâmetro para outra função, sendo desnecessário este procedimento, existe a possibilidade de construir a função diretamente, utilizando função anônima. | object TimerAnonymous {
def oncePerSecond(callback: () => unit) {
while (true) { callback(); Thread sleep 1000 }
}
def main(args: Array[String]) {
oncePerSecond(() =>
println("o tempo corre como um raio..."))
}
}
🗑
|
||||
As classes em Scala podem ter parâmetros. | class Complex(real: Double, imaginary: Double) {
def re() = real
def im() = imaginary
}
🗑
|
||||
Quando não é informada de qual super-classe uma classe deverá ser herdada, é utilizado por padrão 'scala.Object'. | Conforme consta no exemplo abaixo, não foi informado a super-classe, por isso, automaticamente foi usado o padrão 'scala.Object':
class Complex(real: Double, imaginary: Double) {
def re = real
def im = imaginary
}
🗑
|
||||
Pode haver um membro abstrato que é um tipo e um que é valor. | abstract class AbsCell {
type T;
val init: T;
private var value: T = init;
def get: T = value;
def set(x: T): unit = { value = x }
}
val cell = new AbsCell { type T = int; val init = 1 }
🗑
|
||||
A abstração da classe e argumentos é realizada através de parâmetros que são tipos. | def swap[T](x: GenCell[T], y: GenCell[T]): unit = {
val t = x.get; x.set(y.get); y.set(t)
}
🗑
|
||||
Tanto em membros abstratos quanto em genéricos, é possível restringir as especializações que poderão ser usadas. | abstract class Ordered {
type O;
def < (that: O): boolean;
def <= (that: O): boolean =
this < that || this == that
}
abstract class MaxCell extends AbsCell {
type T <: Ordered { type O = T }
def setMax(x: T) = if (get < x) set(x)
}
🗑
|
||||
É possível escrever Scala dentro do XML. | val labPhoneBook =
<phonebook>
<descr>Phone numbers of<b>XML</b> hackers.</descr>
<entry>
<name>Burak</name>
<phone where="work"> +41 21 693 68 67 </phone>
<date> { df.format(new java.util.Date()) } </date>
</entry>
</phonebook>;
🗑
|
||||
Objeto future, representa um valor que ainda não foi retornado por uma mensagem assíncrona. | import scala.actors.Futures._ val eventualmente = future(5 * 42) println(eventualmente())
🗑
|
||||
A linguagem Scala possui o reaproveitamento de threads, sendo assim, se cada ator em um programa usar react, apenas uma única thread será necessária. | def act() { loop { react { case (name: String, actor: Actor) => actor ! getIp(name) case msg => println("Mensagem: " + msg)
🗑
|
||||
é possível criar Scripts Shell utilizando Scala, através de um arquivo '.bat'. | ::#!
@echo off
call scala %0 %*
goto :eof
::!#
Console.println("Hello, world!")
argv.toList foreach Console.println
🗑
|
||||
Os Iteradores permitem que se ande somente um passo na sequência de cada vez, através de métodos abstratos. | trait Iterator[+A] {
def hasNext: Boolean
def next: A
🗑
|
||||
Recurso de interação | [cce]
args.foreach(arg => println(arg))
[/cce]
🗑
|
||||
A sintaxe de declaração de função é simples. | def (parâmetros) =
🗑
|
Review the information in the table. When you are ready to quiz yourself you can hide individual columns or the entire table. Then you can click on the empty cells to reveal the answer. Try to recall what will be displayed before clicking the empty cell.
To hide a column, click on the column name.
To hide the entire table, click on the "Hide All" button.
You may also shuffle the rows of the table by clicking on the "Shuffle" button.
Or sort by any of the columns using the down arrow next to any column heading.
If you know all the data on any row, you can temporarily remove it by tapping the trash can to the right of the row.
To hide a column, click on the column name.
To hide the entire table, click on the "Hide All" button.
You may also shuffle the rows of the table by clicking on the "Shuffle" button.
Or sort by any of the columns using the down arrow next to any column heading.
If you know all the data on any row, you can temporarily remove it by tapping the trash can to the right of the row.
Embed Code - If you would like this activity on your web page, copy the script below and paste it into your web page.
Normal Size Small Size show me how
Normal Size Small Size show me how
Created by:
Bru
Popular Computers sets