gpt4 book ai didi

scala - 递归流抛出 StackOverflowError

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

我根据自身定义流(递归定义)。当试图访问流的第二个元素时,StackOverflowError被抛出。来自Scala控制台的代码:

scala> val s1 = Stream.iterate(1)(identity _)
s1: scala.collection.immutable.Stream[Int] = Stream(1, ?)

scala> lazy val s2 : Stream[Int]= Stream.cons(1, (s2, s1).zipped.map { _ + _ })
s2: Stream[Int] = <lazy>

scala> s1 take 5 print
1, 1, 1, 1, 1, empty
scala> s2(0)
res4: Int = 1

scala> s2(1)
java.lang.StackOverflowError
at $anonfun$s2$1$$anonfun$apply$1.apply(<console>:9)
at $anonfun$s2$1$$anonfun$apply$1.apply(<console>:9)
at scala.Tuple2$Zipped$$anonfun$map$1.apply(Tuple2.scala:62)
at scala.collection.immutable.Stream.foreach(Stream.scala:255)
at scala.Tuple2$Zipped.map(Tuple2.scala:60)
at $anonfun$s2$1.apply(<console>:9)
at $anonfun$s2$1.apply(<console>:9)
at scala.collection.immutable.Stream$Cons.tail(Stream.scala:556)
at scala.collection.immutable.Stream$Cons.tail(Stream.scala:550)
at scala.collection.immutable.Stream.foreach(Stream.scala:256)
at scala.Tuple2$Zipped.map(Tuple2.scala:60)
at $anonfun$s2$1.apply(<console>:9)
at $anonfun$s2$1.apply(<console>:9)
at scala.collection.immutable.Stream$Cons.tail(Stream.scala:556)
at scala.collection.immutable.Str...

我无法理解堆栈溢出的原因。由于流本质上是惰性的,递归映射应该可以工作。

这个场景有什么问题?

我正在使用 Scala 版本 2.8.0.RC2。

最佳答案

问题是zipped并不懒惰——它实际上试图在那里评估该 map 。您可以使用 zip 为所欲为.

scala> val s1 = Stream.iterate(1)(identity _)
s1: scala.collection.immutable.Stream[Int] = Stream(1, ?)

scala> lazy val s2: Stream[Int] = Stream.cons(1, (s2 zip s1).map {s=>s._1+s._2})
s2: Stream[Int] = <lazy>

scala> s2 take 5 print
1, 2, 3, 4, 5, empty

关于scala - 递归流抛出 StackOverflowError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2960605/

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