2017-09-25 23 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