2013-03-26 105 views
0

這個函數應該給出列表中所有數字的總和,但是當我運行它時,我總是得到ans=0這個Scala代碼有什麼問題

def sum(st: List[Int]): Int = { 
    var ans=0 

    def combine(st: List[Int], ans:Int): Int = { 
    if (st.isEmpty) ans else combine(st.tail, ans)   
    } 
    ans 
} 

它有什麼問題?

+0

我知道這不是你要求的,但只是爲了記錄,你也可以調用'st.sum'並得到你的結果。 – Philippe 2013-03-26 15:19:47

回答

5

您需要將列表頭添加到ans。目前你正在遞歸,但實際上並沒有使用列表的頭部。

例如我認爲你需要像下面這樣的東西,其中你將列表的頭部添加到剩餘部分的總和中。

scala> def sum(st: List[Int]): Int = 
    | { 
    | if (st.isEmpty) { 
    | 0 
    | } 
    | else { 
    | st.head + sum(st.tail) 
    | } 
    | } 
sum: (st: List[Int])Int 
+4

另外,它可能有助於_call_結合:) – themel 2013-03-26 14:16:33

2

您已經定義了一個方法combine你的方法sum裏面,但你是不是叫combine(除combine內,所以它不會被調用)。如果您不調用該方法,則不會執行;只是定義方法並不意味着它被執行。

如果你想在功能風格的程序,你也應該避免使用可變變量(var);改用不可變的值(val)。

另外,您的combine方法不會彙總任何內容(它不會在任何地方修改ans或使用列表中的任何值)。

1

我同意Brian回答爲什麼你的解決方案不起作用。

此外,還有一個更短的方式使用Scala的序列(表實現)的API來做到這一點,利用foldLeft:

def sum(st: List[Int]): Int = { 
    st.foldLeft(0)(_ + _) 
} 
3

1)你不是調用內部方法相結合 - 因爲它是iniatilized 0

2)結合並沒有真正做任何事情,你只是回到ANS

我想你想編寫的代碼是以下幾點:

def sum(st: List[Int]): Int = { 
    def combine(st: List[Int], ans:Int): Int = { 
    if (st.isEmpty) ans else combine(st.tail, ans + st.head)   
    } 
    combine(st, 0) 
} 

但當然更短的版本是:

st.foldLeft(0)(_ + _) 

或只是

st.sum 

它使用數字的標準型類的實例:IntIsIntegral:

http://www.scala-lang.org/api/current/index.html#scala.math.Numeric $$ IntIsIntegral $

0

foldLeft,甚至更好,總和是首選選項,如hedefalk提到的。