Created
June 1, 2016 07:23
-
-
Save lhohan/7c6b3335ec76080c06f0c3979155b93c to your computer and use it in GitHub Desktop.
One pass over collection to calculate average
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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