Option Variance

package option

object Variance {

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

  }

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

  def main(args: Array[String]): Unit = {
    val l = List(1, 20, 3, 45, 5, 6, 7.0)
    val l1 = Nil: List[Double]
    println(mean(l))
    println(variance(l))

    println(mean(l1))
    println(variance(l1))
  }
}
Some(12.428571428571429)
Some(209.10204081632648)
None
None

 

posted on 2016-04-24 09:56  JonkeyGuan  阅读(195)  评论(0编辑  收藏  举报