Reputation: 917
I am trying to write a word Count program using Maps in Scala. From various sources on the internet, I found that 'contains', adding elements to the Map using '+' and updating the existing values are valid. But Eclipse gives me errors when I try to use those operations in my code:
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)
}
}
these are the error messages I get in eclipse:
1.)
I tried these operations on REPL and they were working fine without any errors. Any help would be appreciated. Thank you!
Upvotes: 1
Views: 84
Reputation: 375475
You need to instantiate a typed mutable Map (otherwise you're looking for the contains attribute on Map.type
; which isn't there):
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)
}
Note: I also fixed up the lines updating count.
Perhaps this is better written as a 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]
Upvotes: 2