【问题标题】:Spiral example from programming in scala doesn't seem to be workingScala编程的螺旋示例似乎不起作用
【发布时间】:2017-09-25 12:34:09
【问题描述】:

我正在学习 Scala,并且正在使用 Martin Odersky 的“Scala 编程”一书。当我在第 10 章中尝试示例时,它并没有产生预期的结果。我试图在这里和那里修改代码,但没有运气。谁能告诉我哪里出错了?

import Element.elem

object Spiral {
  val space = elem(" ")
  val corner = elem("+")

  def spiral(nEdges: Int, direction: Int): Element = {
    if(nEdges == 1)
      corner
    else {
      val sp = spiral(nEdges - 1, (direction + 3) % 4)
      //println("H: " + sp.height + " W: " + sp.width + " D " + direction)
      def verticalBar = elem('|', 1, sp.height - 1) //updated based on google errata which was otherwise def verticalBar = elem('|', 1, sp.height)
      def horizantalBar = elem('-', sp.width, 1)
      if(direction == 0)
        (corner beside horizantalBar) above (sp beside space)
      else if (direction == 1)
        (sp) beside (corner above verticalBar) //updated based on google errata which was otherwise (sp above space) beside (corner above verticalBar)
      else if (direction == 2)
        (space beside sp) above (horizantalBar beside corner)
      else
        (verticalBar above corner) beside (sp) //updated based on google errata which was otherwise (verticalBar above corner) beside (space above sp)
    }
  }

  //Not working as expected, need to debug and fix
  def main (args: Array[String]) {
    val nSides = args(0).toInt
    println(spiral(nSides, 0))
  }
}

这是以 14 作为参数运行时的预期

+-------------
|             
| +---------+ 
| |         | 
| | +-----+ | 
| | |     | | 
| | | +-+ | | 
| | | + | | | 
| | |   | | | 
| | +---+ | | 
| |       | | 
| +-------+ | 
|           | 
+-----------+ 

我得到了什么

+-------------
| +---------+

【问题讨论】:

  • 什么预期的结果? 会得到什么?
  • 哎呀忘了引用什么不起作用

标签: scala spiral


【解决方案1】:

我认为代码应该是,

def spiral(nEdges: Int, direction: Int): Element = {
if (nEdges == 1)
  elem("+")
else {
  val sp = spiral(nEdges - 1, (direction + 3) % 4)
  def verticalBar = elem('|', 1, sp.height)
  def horizontalBar = elem('-', sp.width, 1)
  if (direction == 0)
    (corner beside horizontalBar) above (sp beside space)
  else if (direction == 1)
    (sp above space) beside (corner above verticalBar)
  else if (direction == 2)
    (space beside sp) above (horizontalBar beside corner)
  else
    (verticalBar above corner) beside (space above sp)
 }
}

我还没有运行这个,请你检查一下它是否有效?

【讨论】:

  • 我首先从书中尝试了这段代码,因为它在谷歌搜索后不起作用,我发现勘误表更新了代码。目前两者都不起作用。
【解决方案2】:

你可能没有更新 Element 类,在上面和旁边的方法中添加了 widen 和 heighten 函数调用。

【讨论】:

  • 欢迎来到 Stack Overflow。如果你有必要的声誉,你可以发表评论。就目前而言,这是一个非常糟糕的答案。请考虑通过添加更多信息(例如代码示例)来加强它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 2012-01-09
  • 2014-02-11
相关资源
最近更新 更多