scala - 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
}}
解决方案
这种事情是用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)
推荐阅读
- sms - SMS Retriever API 不适用于克隆的应用程序
- node.js - MonogDB 从 ubuntu vps 服务器连接到我的本地计算机,但未连接到服务器的 MonogDB
- android - 当我尝试运行默认的颤振应用程序时出现 validateSigningDebug 错误
- php - Remove Child 不包含属性值
- firebase - firestore/permission-denied - 调用者没有执行指定操作的权限。] 在 React Native
- python - drf-yasg 涵盖对以下实施的标准 api 响应的所有响应
- python - 无法在 Kivy Python for windows 中找到任何有价值的窗口提供程序
- javascript - jsPDF jQuery.Deferred 异常:r[o] 未定义
- php - PHP - 如何在函数数组中使用配置文件变量?
- flutter - TabBarView 中的 Flutter Futurebuilder 在选项卡之间切换时在初始应用程序加载后不会触发未来?