1
我正在嘗試使用Scala中的Maps編寫一個單詞計數程序。從互聯網上的各種資源中,我發現'包含',使用'+'向地圖添加元素並更新現有值是有效的。但是Eclipse給我的錯誤,當我嘗試在我的代碼中使用這些操作:Eclipse上的Scala給出了映射操作上的錯誤
object wc {
def main(args:Array[String])={
val story = """ Once upon a time there was a poor lady with a son who was lazy
she was worried how she will grow up and
survive after she goes """
count(story.split("\n ,.".toCharArray()))
}
def count(s:Array[String])={
var count = scala.collection.mutable.Map
for(i <- 0 until s.size){
if(count.contains(s(i))) {
count(s(i)) = count(s(i))+1
}
else count = count + (s(i),1)
}
println(count)
}
}
我在REPL上試過這些操作,它們工作正常,沒有任何錯誤。任何幫助,將不勝感激。謝謝!
這工作!謝謝:) –
那個groupBy真棒!只需一行代碼即可。寫了這麼多的文章讓我覺得很愚蠢。令人驚訝的是多麼緊湊的Scala。非常令人興奮的學習。 :) –