Scala folding (fold)

fold

  • Combine the external elements of the collection and the internal elements of the collection

fold

  • The bottom layer is called foldLeft, which folds from left to right.
  • It is required that the parameter types outside the two collections and the parameter types in the collection must be consistent .
val list1: List[Int] = List(3, 5, 9, 10, 11)
//println(list1.fold(10)(_ + _))  //48
println(list1.fold(6)(_ - _)) //-32

foldLeft

  • Fold from left to right.
  • The parameter types outside the collection can be different from the parameter types in the collection .
println(list1.foldLeft(6)(_ + _)) //44

foldRight

  • Fold from right to left.
  • The parameter types outside the collection can be different from the parameter types in the collection .
  • foldRight is the reverse set, and then foldLeft is called.
println(list1.foldRight(6)(_ - _))  //2

Case study

  • Combine the elements in the two Map collections.

analysis

  • Two different sets are used to fold.
  • One of the parameters is a tuple and the other is a map type, so use foldLeft|foldRight.

achieve

val map1: mutable.Map[String, Int] = mutable.Map("a" -> 1, "b" -> 2, "c" -> 3)
val map2: mutable.Map[String, Int] = mutable.Map("a" -> 2, "b" -> 3, "d" -> 4)

val res = map1.foldLeft(map2) {
    
     (m2, kv) => {
    
    
  val k: String = kv._1
  val v: Int = kv._2
  // 判断map2是否有这个key,有就取出来对应的v和map1的v相加,没有就是0
  m2(k) = m2.getOrElse(k, 0) + v
  m2
}
}

val res2: mutable.Map[String, Int] = map2.foldLeft(map1) {
    
     (m1, kv) => {
    
    
  val k: String = kv._1
  val v: Int = kv._2
  m1(k) = m1.getOrElse(k, 0) + v
  m1
}
}
println(res2)

Guess you like

Origin blog.csdn.net/FlatTiger/article/details/114603520