gpt4 book ai didi

Scala Map.mapValues stackoverflowerror

转载 作者:行者123 更新时间:2023-12-04 14:12:44 27 4
gpt4 key购买 nike

以下代码导致最后一行出现 StackOverflowError。

object StackTest extends App{
@tailrec def incrementValues(acc: Map[String, Int], inc: Int): Map[String, Int] = {
if(inc == 0) acc
else incrementValues(acc.mapValues(_ + 1), inc - 1)
}

val myMap = incrementValues(Map("key" -> 0), 10000)
myMap.foreach(println)
}

在 Scala 2.11.2 中:
Exception in thread "main" java.lang.StackOverflowError
at scala.collection.MapLike$MappedValues.foreach(MapLike.scala:245)
at scala.collection.TraversableLike$WithFilter.foreach(TraversableLike.scala:777)
at scala.collection.MapLike$MappedValues.foreach(MapLike.scala:245)
at scala.collection.TraversableLike$WithFilter.foreach(TraversableLike.scala:777)
at scala.collection.MapLike$MappedValues.foreach(MapLike.scala:245)
...

查看 MapLike 的源代码,我可以看到它使用的是 MappedValues 对象,这看起来像一个 View :
  protected class MappedValues[C](f: B => C) extends AbstractMap[A, C] with DefaultMap[A, C] {
override def foreach[D](g: ((A, C)) => D): Unit = for ((k, v) <- self) g((k, f(v)))
def iterator = for ((k, v) <- self.iterator) yield (k, f(v))
override def size = self.size
override def contains(key: A) = self.contains(key)
def get(key: A) = self.get(key).map(f)
}

/** Transforms this map by applying a function to every retrieved value.
* @param f the function used to transform values of this map.
* @return a map view which maps every key of this map
* to `f(this(key))`. The resulting map wraps the original map without copying any elements.
*/
def mapValues[C](f: B => C): Map[A, C] = new MappedValues(f)

使它实际映射值的最佳方法是什么?

最佳答案

mapValues已知是一个陷阱,因为它确实只创建了一个包装 View 函数,而不是急切地生成一个新集合。因此,在您的示例中,您创建了一个嵌套级别为 10,000 的数据结构。

您可以使用常规 map方法:

acc.map(tup => (tup._1, tup._2 + 1))

或者
acc.map { case (key, value) => (key, value + 1) }

关于Scala Map.mapValues stackoverflowerror,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25450887/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com