2013-12-14 119 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) => ...