首页 > 解决方案 > Scala - 如何在这里避免 var

问题描述

我想知道是否有人知道如何避免以下伪代码中的 var:

var cnt = theConstant
val theSequence = theMap.flapMap{case (theSet, theList) =>
  if (theSet.isEmpty) {
    // do something here with theList and return a sequence
  } else {
    cnt += 1
    // do something here with cnt and theList and return a sequence
  }}

标签: scalafunctional-programmingimmutabilityvar

解决方案


这种事情是用foldLeft. 它以您作为参数提供的任何初始值开始,然后使用元组为集合的每个元素调用您的函数,其中第一个元素是函数评估的先前结果(或初始值),第二个是集合的当前元素。

val (cnt, theSequence) = theMap.foldLeft(0 -> Nil) { 
  case ((cnt, seq), (set, list)) if set.isEmpty => (cnt, seq ++ whateverSequence) 
  case ((cnt, seq), (set, list)) => (cnt + 1, seq ++ whateverSequence)
}

您还可以使用递归解决方案:

@tailrec 
def countAndSeq[K,V,T](in: List[(Set[K], List[V]], cnt: Int = 0, seq: List[T] = Nil) = in match {
  case Nil => cnt -> seq
  case (set, list) :: tail if set.isEmpty => countAndSeq(tail, cnt, seq ++ whatever)
  case (set, list) :: tail => countAndSeq(tail, cnt+1, seq ++ whatever)

}

val (cnt, seq) = countAndSeq(theMap.toList)

推荐阅读