4.2

Implement the variance function in terms of flatMap. If the mean of a sequence is m, the variance is the mean of math.pow(x - m, 2) for each element x in the sequence. See the definition of variance on Wikipedia (http://mng.bz/0Qsr).

def variance(xs: Seq[Double]): Option[Double]

Note: I was not able to solve this problem myself. I learned it from solution and then attempted it

Solution

object Solution extends App {

  println("variance (1,1,1,1): " + variance(Seq(1,1,1,1)))
  println("variance (1,2,3,4): " + variance(Seq(1,2,3,4)))
  println("variance (10,20,30,40): " + variance(Seq(10,20,30,40)))


  def variance(xs: Seq[Double]): Option[Double] =
    mean(xs) flatMap(m => mean(xs.map(x => math.pow(x-m, 2))))

  def mean(xs: Seq[Double]): Option[Double] = 
    if(xs.isEmpty) None
    else Some(xs.sum/xs.length)
}

Output

variance (1,1,1,1): Some(0.0)
variance (1,2,3,4): Some(1.25)
variance (10,20,30,40): Some(125.0)