Scala中的Spiral程序:把代碼都螺旋在一起
作者:Martin Odersky等
本文節(jié)選自Martin Odersky,Lex Spoon和Bill Venners所著,Regular翻譯的《Programming in Scala》的第十章。Scala是一種針對(duì) JVM 將函數(shù)和面向?qū)ο蠹夹g(shù)組合在一起的編程語言。
操練布局庫所有這些元素的好玩兒的方法就是寫一個(gè)畫給定數(shù)量邊界的螺旋的程序。這個(gè)Spiral程序,展示在代碼10.14中,是這么做的:
51CTO編輯推薦:Scala編程語言專題
代碼 10.14 Spiral程序
- import Element.elem
- object Spiral {
- val space = elem(" ")
- val corner = elem("+")
- 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)
- }
- }
- def main(args: Array[String]) {
- val nSides = args(0).toInt
- println(spiral(nSides, 0))
- }
- }
因?yàn)镾piral是個(gè)帶有合適簽名的main方法的獨(dú)立的對(duì)象,所以它是個(gè)Scala程序。Spiral帶一個(gè)命令行參數(shù),一個(gè)整數(shù),并且以特定數(shù)量的邊界畫一個(gè)螺旋。例如,可以像展示在下面的左邊那樣畫一個(gè)六邊界的螺旋,或者右邊的那樣更大的螺旋:(略)
【相關(guān)閱讀】
責(zé)任編輯:book05
來源:
Artima