Scala-如何在这里避免var

时间:2018-07-16 11:05:15

标签: scala functional-programming immutability 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
  }}

1 个答案:

答案 0 :(得分:0)

这类事情是通过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)