2016-06-09 24 views
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) 

} 
} 

這些都是錯誤的消息我在eclipse得到: 1)enter image description here

2)enter image description here

3.)enter image description here

我在REPL上試過這些操作,它們工作正常,沒有任何錯誤。任何幫助,將不勝感激。謝謝!

回答

2

您需要實例化一個類型的可變映射(否則你要尋找的包含Map.type屬性;其不存在):

def count(s: Array[String]) ={ 
    var count = scala.collection.mutable.Map[String, Int]() 
    for(i <- 0 until s.size){ 
    if (count.contains(s(i))) { 
     // count += s(i) -> (count(s(i)) + 1) 
     // can be rewritten as 
     count(s(i)) += 1  
    } 
    else count += s(i) -> 1 
    } 
    println(count) 
} 

注:我也定了更新計數行。


也許這是更好地寫成GROUPBY:

a.groupBy({s: String => s}).mapValues(_.length) 

val a = List("a", "a", "b", "c", "c", "c") 

scala> a.groupBy({s: String => s}).mapValues(_.length) 
Map("b" -> 1, "a" -> 2, "c" -> 3): Map[String, Int] 
+0

這工作!謝謝:) –

+0

那個groupBy真棒!只需一行代碼即可。寫了這麼多的文章讓我覺得很愚蠢。令人驚訝的是多麼緊湊的Scala。非常令人興奮的學習。 :) –

相關問題