[英]Spiral example from programming in scala doesn't seem to be working
我正在學習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作為參數運行時的預期結果
+-------------
|
| +---------+
| | |
| | +-----+ |
| | | | |
| | | +-+ | |
| | | + | | |
| | | | | |
| | +---+ | |
| | | |
| +-------+ |
| |
+-----------+
我得到什么
+-------------
| +---------+
我認為代碼應該是
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)
}
}
我還沒有運行,請您檢查一下是否可行?
您可能沒有更新Element類,而是在方法上方和旁邊添加了widen和heightn函數調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.