【发布时间】:2012-09-08 04:00:21
【问题描述】:
我想知道演员如何将值返回给发送者以及如何将其存储在变量中。
例如,假设我们必须找到 2 个数字的平方和并打印出来。
即总和 = a2 + b2
我有两个演员。 1 个参与者计算传递给它的任何数字的平方(例如,SquareActor)。另一个参与者将两个数字 (a , b) 发送到 SquareActor 并计算它们的总和(例如,SumActor)
/** Actor to find the square of a number */
class SquareActor (x: Int) extends Actor
{
def act()
{
react{
case x : Int => println (x * x)
// how to return the value of x*x to "SumActor" ?
}
}
}
/** Actor to find the sum of squares of a and b */
class SumActor (a: Int, b:Int) extends Actor
{
def act()
{
var a2 = 0
var b2 = 0
val squareActor = new SquareActor (a : Int)
squareActor.start
// call squareActor to get a*a
squareActor ! a
// How to get the value returned by SquareActor and store it in the variable 'a2' ?
// call squareActor to get b*b
squareActor ! b
// How to get the value returned by SquareActor and store it in the variable 'b2' ?
println ("Sum: " + a2+b2)
}
}
如果以上这些都不可能,请原谅我;我认为我对演员的基本理解本身可能是错误的。
【问题讨论】:
-
我对符号数学非常感兴趣,这段代码对于方程求解器来说看起来非常优雅和简洁,但我看不到它如何求解方程?在我看来它只是计算一个基本函数?
标签: scala actor message-passing