简体   繁体   English

来自Scala编程的螺旋示例似乎不起作用

[英]Spiral example from programming in scala doesn't seem to be working

I am learning Scala and was using Programming in Scala book by Martin Odersky. 我正在学习Scala,并且正在使用Martin Odersky写的《在Scala中编程》一书。 When I was trying example in Chapter 10 it isn't producing the expected result. 当我尝试第10章中的示例时,它并没有产生预期的结果。 I tried to modify the code a bit here and there with no luck. 我试图在这里和那里稍微修改一下代码,但是没有运气。 Can anyone tell me where I am going wrong? 谁能告诉我我要去哪里错了?

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))
  }
}

Here is the expected when run with 14 as argument 这是使用14作为参数运行时的预期结果

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

What I am getting 我得到什么

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

I think the code should be , 我认为代码应该是

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)
 }
}

I haven't run this, could you please check if this works ? 我还没有运行,请您检查一下是否可行?

您可能没有更新Element类,而是在方法上方和旁边添加了widen和heightn函数调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM