Skip to content

Instantly share code, notes, and snippets.

@lhohan
Created June 1, 2016 07:23
Show Gist options
  • Save lhohan/7c6b3335ec76080c06f0c3979155b93c to your computer and use it in GitHub Desktop.
Save lhohan/7c6b3335ec76080c06f0c3979155b93c to your computer and use it in GitHub Desktop.
One pass over collection to calculate average
def sumLength(xs: List[Int]) = xs.foldLeft(None:Option[(Int,Int)]){
case (None, x) => Some(x, 1)
case (Some((s:Int, l:Int)), x) => Some((s + x, l + 1 ))
}
def avg(xs: List[Int]): Option[Int] = sumLength(xs).map{case (sum, length) => sum / length}
val avg1 = avg(List(1, 2, 3, 4, 6, 7, 8, 9))
val avg2 = avg(List(1, 2, 3, 4, 5, 6, 7, 8, 9))
val avg3 = avg(List.empty[Int])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment