2013-06-03 33 views
0

我有一個問題,這部分代碼在斯卡拉如何正確使用摺疊留在斯卡拉功能

object Test12 { 
    def times(chars: List[Char]): List[(Char, Int)] = { 
    val sortedChars = chars.sorted 
    sortedChars.foldLeft (List[(Char, Int)]()) ((l, e) => 
     if(l.head._1 == e){ 
      (e, l.head._2 + 1) :: l.tail 
     } else { 
      (e, 1) :: l 
     }) 
    } 

    val s = List('a', 'b') 

    val c = times s 
} 

最後一行給出一個錯誤:

的方法次缺少參數;按照這個方法用'_」如果你 希望把它當作一個部分應用功能

但是,我不明白爲什麼,因爲我已經給2個參數到最後一個功能 - foldLeft。

在此先感謝您的幫助!

代碼的想法是計算每個角色有多少時間出現在給定列表

回答

3

時代的語法是好的,但你需要使用括號調用它時,即:

val c = times(s) 

但它不會工作,因爲你使用l.head不檢查如果L是零,而一個空的列表沒有頭。你可以例如與之相匹配的檢查爲:

def times(chars: List[Char]): List[(Char, Int)] = { 
    val sortedChars = chars.sorted 
    sortedChars.foldLeft (List[(Char, Int)]()) ((a,b) => (a,b) match { 
    case (Nil, e) => (e, 1) :: Nil 
    case ((e, count) :: l, f) => 
     if (e == f) (e, count + 1) :: l 
     else (f, 1) :: (e, count) :: l 
    }) 
} 

雖然更簡單的方法是使用更高級別的採集功能:

def times(chars: List[Char]) = chars.groupBy(c=>c).map(x=>(x._1,x._2.length)).toList 
+0

太謝謝你了! :-) – Joggi

1
val c = times s 

您不能調用方法沒有這樣的支架。試試times(s)this times s