Friday, June 5, 2020

Scala foldLeft and foldRight

According to my experience, one of the best ways to workout the intuition is to see how it works on the very simple examples:
List(1, 3, 8).foldLeft(100)(_ - _) : Explanation:((100 - 1) - 3) - 8 == 88
List(1, 3, 8).foldRight(100)(_ - _): Explanation:  1 - (3 - (8 - 100)) == -94
As you can see, foldLeft/Right just passes the element of the list and the result of the previous application to the the operation in second parentheses. It should be also mentioned that if you apply these methods to the same list, they will return equal results only if the applied operation is associative.
More examples
class Foo(val name: String, val age: Int, val sex: Symbol)

object Foo {
  def apply(name: String, age: Int, sex: Symbol) = new Foo(name, age, sex)
}

val fooList = Foo("Hugh Jass", 25, 'male) ::
              Foo("Biggus Dickus", 43, 'male) ::
              Foo("Incontinentia Buttocks", 37, 'female) ::
              Nil
              
              
val stringListFoldRight = fooList.foldRight(List[String]()) { ( f,z) =>
  val title = f.sex match {
    case 'male => "Mr."
    case 'female => "Ms."
  }
  z :+ s"$title ${f.name}, ${f.age}"
}

println(stringListFoldRight) 
//List(Ms. Incontinentia Buttocks, 37, Mr. Biggus Dickus, 43, Mr. Hugh Jass, 25)

val stringListFoldLeft = fooList.foldLeft(List[String]()) { (z,f) =>
  val title = f.sex match {
    case 'male => "Mr."
    case 'female => "Ms."
  }
  z :+ s"$title ${f.name}, ${f.age}"
}

println(stringListFoldLeft) 
//List(Mr. Hugh Jass, 25, Mr. Biggus Dickus, 43, Ms. Incontinentia Buttocks, 37)



No comments:

Post a Comment

Recent Post

Databricks Delta table merge Example

here's some sample code that demonstrates a merge operation on a Delta table using PySpark:   from pyspark.sql import SparkSession # cre...