2017-08-24 23 views
0

當我設置一個變量等於一個函數時,我在這段代碼中只剩下一個錯誤,這在我認爲Scala中很常見。任何人都可以告訴我爲什麼我得到一個非法的簡單表達式錯誤的開始?此外,請打開一些關於如何簡化此代碼的建議。在Scala(斐波納契函數)中非法啓動簡單表達式

import scala.collection.mutable.ListBuffer 

object FibFunction { 

    def main(args: Array[String]): Unit = { 

    println(fibinacci(10)) 

    } 

    def fibinacci(start: Int): ListBuffer[Int] = { 

    val x = 0 
    val y = 1 
    var z = x + y 
    val result: ListBuffer[Int] = new ListBuffer[Int] 
    var len = start - 3 
    result += 0 
    result += 1 
    result += z 

    val finalResult: ListBuffer[Int] = def finish(len: Int, y: Int, z: Int, resultList: ListBuffer[Int] = result): ListBuffer[Int] = { 
     var iter2: Int = len 
     var newnum = 0 
     var first = y 
     val second = z 
     if (iter2 <= 0) return resultList; 
     else { 
     iter2 -= 1; 
     newnum = first + second; 
     resultList += newnum; 
     finish(iter2, second, newnum, resultList) 

     } 

     return resultList 

    } 

    finalResult 
    } 
} 
+0

順便說一句,是斐波那契,不是斐波那契 –

回答

0

這不是你如何得到函數的結果。

首先定義函數:

def finish(len: Int, y: Int, z: Int, resultList: ListBuffer[Int]): ListBuffer[Int] = { 

    var iter2: Int = len 
    var newnum = 0 
    var first = y 
    val second = z 
    if (iter2 > 0) { 
    iter2 -= 1; 
    newnum = first + second; 
    resultList += newnum; 
    finish(iter2, second, newnum, resultList) 

    } 
    resultList 
} 

然後調用函數

val finalResult: ListBuffer[Int] = finish(len, y, z, result) 

Scala是什麼,但不落俗套。使用與編寫和調用函數相同的技巧,scala會很好。

+1

就像一個魅力。非常感謝你! – wayneeusa