我正在与scala一起工作,并希望创建一个具有向地图上递归添加一些功能的类。
class Index(val map: Map[String, String]) {
def add(e: (String, String)): Index = {
Index(map + (e._1 -> e._2))
}
def addAll(list: List[(String, String)], index: Index = Index()): Index = {
list match {
case ::(head, next) => addAll(next, add(head))
case Nil => index
}
}
}
object Index {
def apply(map: Map[String, String] = Map()) = {
new Index(map)
}
}
val index = Index()
val list = List(
("e1", "f1"),
("e2", "f2"),
("e3", "f3"),
)
val newIndex = index.addAll(list)
println(newIndex.map.size.toString())
由于该函数应该在地图上添加3个条目,所以我将该代码打印为3,但实际输出为1。我在做什么错以及如何解决?
在线小提琴:https : //scalafiddle.io/sf/eqSxPX9/0
在您add(head)
应该调用的地方有一个简单的错误index.add(head)
。
但是,在编写这样的递归例程时,最好使用嵌套方法,例如:
def addAll(list: List[(String, String)]): Index = {
@annotation.tailrec
def loop(rem: List[(String, String)], index: Index): Index = {
rem match {
case head :: tail => loop(tail, index.add(head))
case Nil => index
}
}
loop(list, Index())
}
这使函数可以进行尾部递归并由编译器进行优化,并且还避免了对该addAll
方法的虚假参数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句