Calculate average and standard deviation in Scala

I needed to have class that will help me to calculate average and standard deviation of some numbers. Something which should work like this:

val c = new Calculator();
for(i <- 1 to 10) c.add(i);
c.avg;
c.stdDev;

Wrote simple class Calculator.scala and it returns:

scala> res1: String = Calculator -> 1.0 2.0 3.0 4.0 5.0 6.0
scala> res2: Double = 3.5
scala> res3: Double = 1.8708286933869707

Source could be found here:

import collection.mutable.ArrayBuffer

class Calculator(){
  val numbers = new ArrayBuffer[Double]();
  def add(number:Double):Unit = {
    numbers += number;
  }
  def avg():Double = {
      var sum:Double = 0.0;
      for(x:Double <- numbers){
        sum = sum + x;
      }
      sum/numbers.length;
  }
   // Thanks to Christopher Martin
  def avg_short:Double = numbers.reduceLeft(_ + _) / numbers.length

  def stdDev():Double = {
      var sum:Double    = 0.0;
      if(numbers.length>=2){
        val mean = avg();
        val factor:Double = 1.0/(numbers.length.toDouble-1);
        for(x:Double <- numbers){
          sum = sum + ((x-mean)*(x-mean));
        }
        sum = sum * factor;
      }
      return Math.sqrt(sum);
  }
  def print():String = {
    var result:String = "";
    result = result + "Calculator -> ";
    for(x <- numbers) result = result + x +" ";
    return result;
  }
  def reset():Unit = {
    numbers.clear();
  }
}

Scala – retrieve data from XML

I started learning Scala 2 months ago, because Groovy’s performance was too low for my purpose -> modelling epidemies on cellular automata.
Appeared a need to throw variables – important for epidemy simulation – to external file.
Scala provides simple interface to use XML data.
Below you can find examples how to retrieve data from XML.
It’s very convenient to work with Scala through console:

scala> x
res5: scala.xml.Elem = 

       0.01
       0.4
       0.5
       
            0.7
       

Get “init” node in 2 ways:

scala> x \\ "init"
res15: scala.xml.NodeSeq = 0.01

scala> x \ "init"
res16: scala.xml.NodeSeq = 0.01

Get “individual” node in 2 ways:

scala> x \\ "individual"
res17: scala.xml.NodeSeq = 0.7

scala> x \ "die" \ "individual"
res23: scala.xml.NodeSeq = 0.7

Conclusion:

  • “\” is used to search through first level of node’s children
  • “\\” is used to search through every level od node’s children.

Get “init” value :

scala> (x \ "init").text
res19: String = 0.01

scala> (x \ "init").text.toDouble
res20: Double = 0.01

Get “individual” value:

scala> (x \ "die" \ "individual").text
res22: String = 0.7

Similarly you can get attribute:

scala> x \ "recover" \ "@tip"
res28: scala.xml.NodeSeq = const|individual

scala> (x \ "recover" \ "@tip").text
res29: String = const|individual

If you would like to react on specific value in attribute use:

scala> (x \ "recover" \ "@src").text match{
                                            case "const" => true;
                                            case "individual" => false;
                                            case _ => false;
                                        }
res31: Boolean = true

Scala – save file to disk

var path:String = new File("./").getCanonicalPath+"/"
var file:String = path+"fileName.txt"
val writer = new PrintWriter( BufferedWriter(new FileWriter(file,false)));
writer.print(temp+" ")
writer.println("")
writer.close()

Make jar from your Scala application

Best solution i found is:
http://stackoverflow.com/questions/809138/creating-a-jar-file-from-a-scala-file

It’s worth looking also:
http://jlaskowski.blogspot.com/2008/04/pierwsze-spotkanie-ze-scal-lektura.html

You can do that in very convenient way by using FREE
Java/Scala/Groovy IDE -> IntellijIDEA 9 Community Edition

Download it: http://www.jetbrains.com/idea/download/
And learn how to use artifacts:  http://blogs.jetbrains.com/idea/tag/artifacts/