summaryrefslogtreecommitdiff
path: root/docs/examples/actors/customer.scala
blob: 32787092d12d34677785bed63f635740ef963123 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
 * @author Philipp Haller <philipp.haller@epfl.ch>
 *
 * This shows "customer passing" for implementing
 * recursive algorithms using actors.
 */

package examples.actors

import scala.actors.single.Actor

case class Factorial(n: int, resTo: Actor[int])

class FactorialProcess extends Actor[Factorial] {
  override def run: unit = {
    receive {
      case Factorial(n, resTo) =>
        if (n == 0) {
          resTo ! 1
        }
        else {
          val m = new MultiplyActor(n, resTo)
          m.start()
          this ! Factorial(n-1, m)
        }
        run
    }
  }
}

class MultiplyActor(factor: int, resTo: Actor[int]) extends Actor[int] {
  override def run: unit =
    receive {
      case value: int =>
        resTo ! factor * value
    }
}

object CustomerPassing {
  def main(args: Array[String]): unit = {
    val fac = new FactorialProcess
    fac.start()

    val c = new Actor[int] {
      override def run: unit = {
        fac ! Factorial(3, this)

        receive {
          case value: int =>
            System.out.println("Result: " + value)
        }
      }
    }
    c.start()
  }
}