Skip to content

Instantly share code, notes, and snippets.

@faermanj
Created March 28, 2012 13:47
Show Gist options
  • Save faermanj/2226303 to your computer and use it in GitHub Desktop.
Save faermanj/2226303 to your computer and use it in GitHub Desktop.
exploring-scala-2
object Colecoes extends Application {
val myList = List.range(-5, 5)
CollectionUtils.forAllDo(
CollectionUtils.collect(
CollectionUtils.select(myList,
new Predicate() {
def evaluate(obj: Object): Boolean =
return obj.asInstanceOf[Int] > 0;
}), new Transformer() {
def transform(obj: Object): Object = {
return (2 * obj.asInstanceOf[Int])
.asInstanceOf[Object];
}
}),
new Closure() {
def execute(obj: Object) {
println(obj);
}
})
}
object ParCol{
def main(args: Array[String]) {
(1 to 5).foreach(println);
(1 to 5).par.foreach(println);
}
}
case object Calculate
case object ShutDown
class Calculator extends Actor {
val rand = new Random
var pi, in, cnt = 1.0
def act() {
while (true) {
receive {
case Calculate =>
sender ! estimativeOfPi
case ShutDown => exit
}
}
}
def estimativeOfPi: Double = {
val x = rand.nextDouble - 0.5
val y = rand.nextDouble - 0.5
cnt += 1.0;
if (sqrt(x * x + y * y) < 0.5) in += 1
return in / cnt * 4
}
}
class Coordinator(numOfCalculators: Int) extends Actor {
def act() {
val startedAt = currentTimeMillis
var calculators = List.fill(numOfCalculators)(new Calculator)
calculators.foreach(c => {
c.start
c ! Calculate
})
while (true) {
receive {
case estimative: Double =>
val error = abs(Pi - estimative)
if (error > 0.0000001)
sender ! Calculate
else {
val tempo = currentTimeMillis - startedAt
calculators.foreach(_ ! ShutDown)
println("Pi found by " + sender + " = " + estimative)
println("Execution time: " + tempo)
exit
}
}
}
}
}
object PiActors {
def main(args: Array[String]) {
new Coordinator(2).start
}
}
@WebServlet(Array("/mostraParams"))
class PrintParametersServlet extends HttpServlet {
override def doGet(req: HttpServletRequest,
resp: HttpServletResponse) {
val out = resp.getWriter();
req.getParameterMap()
.map {case (key, value) => key +" = "+ value.mkString(",")}
.foreach(out.println(_))
}
}
myList.filter(_ > 0).map(_ * 2).foreach(println(_));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment