2013-12-14 51 views
0

我必須編寫一個代碼,以使Actor A產生Actor B消耗的無限數量的數字流。演員A輸出序列:x,f(x),g(f(x))等,其中f(x)= 10,如果x是0,否則3x,其中g(x)是x/2。即:處理無限數量的消息(akka)

輸出:x = 0,f(x)= 10,g(f(x)= 5(3個消息),則接下來的3個消息應該是f(g(f(x)),g(f (g(f(x))),f(g(f(g(f(x))))和它們的值...其中內部函數變爲x每次計算相鄰結果的結果

在一個時間與數字3

演員乙優惠和它應該打印每個三列上與平均3個數字的同一條線上。

(0)被傳遞給ActorA從主方法的值。

我的嘗試:

import akka.actor._ 

class ActorA(processB:ActorRef) extends Actor with ActorLogging{ 

    def f(x : Int) = if(x == 0) 10 else 3 * x 
    def g(x : Int) = x/2 

    def receive = { 
    case 0 => 
     val x = 0 
     //processB ! (x) 
    // processB ! (f(x)) 
    // processB ! (g(f(x))) 
     println((f(x))) 
     println((g(f(x)))) 
    /*case Stop => 
     Console.println("Stop") 
     processB ! Stop 
     context stop self */ 
    } 
} 

class ActorB extends Actor with ActorLogging{ 

def receive = { 
     case ActorA => 


     case Stop => 
      Console.println("Stop") 
      exit()  
} 
} 

case object ActorA 
case object ActorB 
case object Stop 

object messages { 
    def main(args: Array[String]) :Unit = { 
    val system = ActorSystem("actors") 
    val processB = system.actorOf(Props[ActorB]) 
    val actorA = system.actorOf(Props(new ActorA(processB))) 
    actorA ! 0 
    } 
} 

如何生成無限數量的消息,我可以一次處理3個消息嗎?謝謝

回答

2

要獲得無限序列,您可以使用Stream

德里克悅對他們一個很好的博客文章,以及如何生成斐波那契數的工作原理:

http://www.derekwyatt.org/2011/07/29/understanding-scala-streams-through-fibonacci/

您可以使用相同的基本原則,爲您的序列,如果我理解正確,交替應用f和g對流中的前一個值起作用。

您可以編寫如下:

lazy val stream: Stream[Int] = x #:: stream.zipWithIndex.map { 
    case (p,i) => if (i%2 == 0) f(p) else g(p) 
} 

然後,您可以使用grouped流拆分成3塊, 在這裏,我已經做了,然後轉換所產生的Stream[Int],每個大小爲3,爲方便起見,一個元組:

val chunks: Iterator[(Int,Int,Int)] = stream.grouped(3).map { s => 
    (s.head, s.tail.head, s.tail.tail.head) 
} 

然後,您可以使用該但是你想,如果你願意的話發送元組到其他演員。

在另一側則可以按如下匹配元組:

case (a:Int, b:Int, c:Int) => ...