Tuesday 19 August 2014

Scala Note 10: reduceLeft method in Scala


The reduceLeft method words by applying the function/operation you give it, and applying it to successive elements in the collection. The result of the first comparison is used in the second comparison, and so on. It works from left to right, beginning with the first element in the collection.

// returns the max of the two elements
val findMax = (x: Int, y: Int) => {
  val winner = x max y
  println("compared %d to %d, %d was larger".format(x,y,winner))
  winner
}
val a = Array(12, 6, 15, 2, 20, 9)
scala> a.reduceLeft(findMax)
compared 12 to 6, 12 was larger
compared 12 to 15, 15 was larger
compared 15 to 2, 15 was larger
compared 15 to 20, 20 was larger
compared 20 to 9, 20 was larger
res0: Int = 20






Reference:

http://alvinalexander.com/scala/scala-reduceleft-examples

No comments:

Post a Comment