Addded method 'context' to UntypedActor. Changed the Pi calculation to use tail-recursive function

This commit is contained in:
Jonas Bonér 2011-04-06 10:45:48 +02:00
parent eb5a38cd69
commit cea277ea58
2 changed files with 14 additions and 7 deletions

View file

@ -4,14 +4,8 @@
package akka.actor
import akka.dispatch._
import akka.config.Supervision._
import akka.japi.{Creator, Procedure}
import java.net.InetSocketAddress
import scala.reflect.BeanProperty
/**
* Subclass this abstract class to create a MDB-style untyped actor.
* <p/>
@ -63,6 +57,7 @@ import scala.reflect.BeanProperty
abstract class UntypedActor extends Actor {
def getContext(): ActorRef = self
def context(): ActorRef = self
final protected def receive = {
case msg => onReceive(msg)
@ -88,4 +83,4 @@ abstract class UntypedActor extends Actor {
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
trait UntypedActorFactory extends Creator[Actor]
trait UntypedActorFactory extends Creator[Actor]

View file

@ -13,6 +13,8 @@ import akka.dispatch.Dispatchers
import System.{currentTimeMillis => now}
import java.util.concurrent.CountDownLatch
import scala.annotation.tailrec
/**
* First part in Akka tutorial.
* <p/>
@ -57,6 +59,7 @@ object Pi extends App {
class Worker() extends Actor {
// define the work
/*
// FIXME tail-recursive fun instead
val calculatePiFor = (arg: Int, nrOfElements: Int) => {
val range = (arg * nrOfElements) to ((arg + 1) * nrOfElements - 1)
@ -66,6 +69,15 @@ object Pi extends App {
// Use this for more functional style but is twice as slow
// range.foldLeft(0.0D)( (acc, i) => acc + 4 * math.pow(-1, i) / (2 * i + 1) )
}
*/
def calculatePiFor(arg: Int, nrOfElements: Int): Double = {
val end = (arg + 1) * nrOfElements - 1
@tailrec def doCalculatePiFor(cursor: Int, acc: Double): Double = {
if (end == cursor) acc
else doCalculatePiFor(cursor + 1, acc + (4 * math.pow(-1, cursor) / (2 * cursor + 1)))
}
doCalculatePiFor(arg * nrOfElements, 0.0D)
}
def receive = {
case Work(arg, nrOfElements) =>