Skip to content

Instantly share code, notes, and snippets.

@oreillyross
Last active August 29, 2015 14:07
Show Gist options
  • Save oreillyross/3279424a0d64bb98b130 to your computer and use it in GitHub Desktop.
Save oreillyross/3279424a0d64bb98b130 to your computer and use it in GitHub Desktop.
FoldLeft examples
// Sum ints
def sum(ints: List[Int]): Int = ints.foldLeft(0)((a,b) => a + b)
def sum(ints:List[Int]): Int = ints.foldLeft(0)(_+_)
// find average from a list of Double
def average(list: List[Double]): Double =
list.foldLeft(0.0)(_+_) / list.foldLeft(0.0)((r,c) => r+1)
def average(list: List[Double]): Double = list match {
case head :: tail => tail.foldLeft( (head,1.0) )((r,c) =>
((r._1 + (c/r._2)) * r._2 / (r._2+1), r._2+1) )._1
case Nil => NaN
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment