Tag Archives: Scala

Scala Fold operation Explained!

Fold takes the data in one format and returns in other,Fold on list takes a initial value and function with two arguments that is to be applied to all the elements of the list.
In initial iteration the initial value (Zero/neutral value) passed as the first argument of the function while the current element of the list on which we are iterating as the second argument,In the next iteration the result of the fist iteration is passed to the first argument while the current element to the second and the process goes on
Below is an example of finding maximum from a list of elements in scala

we have passed the value at position 0 of the list as the initial value
In first Iteration
the value at 0 position i.e 2 is passed as first argument to function i.e assigned to min
the current value on which we are iterating is 2 this is assigned to max as the second argument to function

In Second Iteration
the result of the first iteration i.e 2 is passed as the first argument to the function i.e assigned to min
the current value on which we are iterating i.e 1 is passed as the second parameter to function i.e assigned to max

and the story goes on ….. 🙂

package example

/**
* @author amith2
*/
object ScalaFoldMIn {
def main(args: Array[String]): Unit = {
val scalaData=List(2,1,3,5)
println(scalaData.fold(scalaData(0))((min,max)=>{
if(min<max)
min
else
max
}))
}
}