2017-09-25 22 views
0

我正在学习Scala,并且正在使用Martin Odersky编写的Scala书籍。当我在第10章中尝试示例时,它不会产生预期结果。我试着在这里和那里修改代码,但没有运气。谁能告诉我我要去哪里?Spala编程中的螺旋示例似乎不起作用

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个为参数运行的预期

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

什么我得到

+------------- 
| +---------+ 
+0

什么是预期结果?你得到了什么? –

+0

哎呀忘了引用什么不工作 – Rukmaj

回答

0

我认为代码应该是,

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

我没有运行过这个,请问你可以请chec k如果这有效?

+0

我第一次尝试从书中的代码,因为它不工作后,谷歌搜索我在哪里找到勘误更新代码。两者目前都没有工作。 – Rukmaj