title: Scala: What is the generic way to calculate standard deviation
body: <p>I am curious as to how I can write a generic method to calculate standard deviation and variance in scala. I have a generic method for calculating mean (stolen from here: <a href="https://stackoverflow.com/questions/6188990/writing-a-generic-mean-function-in-scala">Writing a generic mean function in Scala</a>)</p>
  
  <p>I have tried to convert the mean calculation to get standard deviation and variance but it looks wrong to me. Generics are WAY beyond my skills in Scala programming at the moment.</p>
  
  <p>The code for calculating the mean, standard deviation and variance is this:</p>
  
  <pre><code>package ca.mikelavender
  
  import scala.math.{Fractional, Integral, Numeric, _}
  
  package object genericstats {
  
    def stdDev[T: Numeric](xs: Iterable[T]): Double = sqrt(variance(xs))
  
    def variance[T: Numeric](xs: Iterable[T]): Double = implicitly[Numeric[T]] match {
      case num: Fractional[_] =&gt; {
        val avg = mean(xs)
        num.toDouble(
          xs.foldLeft(num.zero)((b, a) =&gt;
            num.plus(b, num.times(num.minus(a, avg), num.minus(a, avg))))) /
          xs.size
      }
      case num: Integral[_] =&gt; {
        val avg = mean(xs)
        num.toDouble(
          xs.foldLeft(num.zero)((b, a) =&gt;
            num.plus(b, num.times(num.minus(a, avg), num.minus(a, avg))))) /
          xs.size
      }
    }
  
    /**
      * https://stackoverflow.com/questions/6188990/writing-a-generic-mean-function-in-scala
      */
    def mean[T: Numeric](xs: Iterable[T]): T = implicitly[Numeric[T]] match {
      case num: Fractional[_] =&gt; import num._; xs.sum / fromInt(xs.size)
      case num: Integral[_] =&gt; import num._; xs.sum / fromInt(xs.size)
      case _ =&gt; sys.error("Undivisable numeric!")
    }
  
  }
  </code></pre>
  
  <p>I feel like the match case in the variance method is not needed or could be more elegant. That is, the duplicity of the code seems very wrong to me and that I should be able to just use the match to get the numeric type and then pass that on to a single block of code that does the calculation.</p>
  
  <p>The other thing I don't like is that it always returns a <code>Double</code>. I feel like it should return the same input numeric type, at least for the Fractional values.</p>
  
  <p>So, are there any suggestions on how to improve the code and make it prettier?</p>