【问题标题】:Array.tabulate StackOverFlowErrorArray.tabulate StackOverFlowError
【发布时间】:2013-09-26 19:49:22
【问题描述】:

我是 Scala 的新手,我正在使用 Array.tabulate 方法。执行这段简化的代码 sn-p 时出现 StackOverFlowError(最初是 dp 问题)。

  import Lazy._

  class Lazy[A](x: => A) {
    lazy val value = x
  }

  object Lazy {
    def apply[A](x: => A) = new Lazy(x)
    implicit def fromLazy[A](z: Lazy[A]): A = z.value
    implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)
  }

  def tabulatePlay(): Int = {
    lazy val arr: Array[Array[Lazy[Int]]] = Array.tabulate(10, 10) { (i, j) =>
      if (i == 0 && j == 0)
        0 // some number
      else
        arr(0)(0)
    }
    arr(0)(0)
  }

调试时,我注意到由于 arr 是惰性的,当它到达 arr(0)(0) 表达式时,它会尝试通过再次调用 Array.tabulate 方法来评估它——无限地一遍又一遍。

我做错了什么? (我更新了代码 sn-p,因为我是基于 Dynamic programming in the functional paradigm 中给出的解决方案,特别是 Antal S-Z 的答案)

【问题讨论】:

    标签: arrays scala scala-2.10


    【解决方案1】:

    你已经有效地导致了无限递归。您根本无法从其自己的初始化代码中引用lazy val。您需要单独计算arr(0)(0)

    【讨论】:

    • 查看我更新的帖子。为什么它在我引用但不是我的帖子中有效?谢谢。
    • @xxtommoxx 您指的是哪个特定答案?
    • 抱歉忘了提Antal S-Z的回答
    • @xxtommoxx 好吧,现在您问题中的代码与原始代码完全不同...
    【解决方案2】:

    我不确定您为什么要在构建 arr 之前尝试访问它,tabulate 似乎用于用函数填充数组 - 调用 arr 总是会导致无限递归。

    在此处查看 Rex 的示例(并为他投票),也许这会有所帮助。

    In a multidimensional sequence created with tabulate, is the innermost seq the 1. dimension?

    【讨论】:

      【解决方案3】:

      我能够通过在 Lazy 中包装 arr(0)(0) 来解决这个问题,因此它被评估为按名称调用的参数,因此不在 tabulate 方法中评估 arr。我引用的代码是使用隐式(二进制 + 运算符)自动转换它的,所以它不是很明确。

       def tabulatePlay(): Int = {
          lazy val arr: Array[Array[Lazy[Int]]] = Array.tabulate(10, 10) { (i, j) =>
            if (i == 0 && j == 0)
              1 // some number
            else
              new Lazy(arr(0)(0))
          }
          arr(0)(0)
        }
      

      谢谢大家。

      【讨论】:

        猜你喜欢
        • 2012-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-22
        • 2014-02-03
        • 2014-08-27
        • 2018-10-09
        • 1970-01-01
        相关资源
        最近更新 更多