Boa tarde professor.
Seria possível disponibilizar a solução do segundo teste.
Cumprimentos,
Carlos Passos
Boa tarde professor.
Seria possível disponibilizar a solução do segundo teste.
Cumprimentos,
Carlos Passos
Olá.
1. Pipeline
import scala.actors._
import scala.actors.Actor._
case class Request(x: Int)
case class Result(x: Int)
case object Length
case object Stop
case class Request2(x: Int, client: OutputChannel[Any])
case class Length2(n: Int, client: OutputChannel[Any])
abstract class Pipe extends Actor {}
class Eval(f: Int=>Int, next: Pipe) extends Actor {
def act() {
loop { react {
case Request2(x, client) =>
val res = f(x)
if( next == null )
client ! Result(res)
else
next ! Request2(res, client)
exit()
} }
}
}
class Stage(f: Int=>Int, next: Pipe) extends Pipe {
def act() {
loop { react {
case Request(x) =>
self ! Request2(x, sender)
case Length =>
self ! Length2(1, sender)
case Stop =>
if( next != null )
next ! Stop
reply()
exit()
case Request2(x, client) =>
val helper = new Eval(f, next)
helper.start
helper ! Request2(x, client)
case Length2(n, client) =>
if( next == null )
client ! Result(n)
else
next ! Length2(n+1, client)
} }
}
}
object Pipe { // singleton non-actor
def buildAndStart(fs: List[Int=>Int]): Pipe = {
fs match {
case Nil => null
case x::xs => {
val s = new Stage(x, buildAndStart(xs))
s.start()
s
}
}
}
def request(s: Pipe, x: Int): Int = {
s !? Request(x) match { case Result(x) => x ; case _ => error("error") }
}
def length(s: Pipe): Int = {
s !? Length match { case Result(x) => x ; case _ => error("error") }
}
def stop(s: Pipe): Unit = {
s !? Stop
}
}
def test = {
val pipe = Pipe.buildAndStart(List(x=>x+1, x=>x+1, x=>x+1, x=>x+2, x=>x/2))
println(Pipe.length(pipe))
println(Pipe.request(pipe, 0))
println(Pipe.request(pipe, 9))
Pipe.stop(pipe)
}