I am very new to Scala and would appreciate any help (looked everywhere and spent the last 8 hours trying to figure it out)
I currently have
def apply(file: String) : Iterator[String] = {
scala.io.Source.fromFile(file).getLines().map(_.toLowerCase)
}
Like
def groupFreq[A,B](xs: Iterator[A], f: A => B): HashMap[B, Int] = {
var freqMap = new HashMap[B, Int]
for (x <- xs) freqMap = freqMap + ( f(x) -> ( freqMap.getOrElse( f(x) , 0 ) +1 ) )
freqMap
}
apply simply takes the word file we pass.
GroupFreq accepts xs: Iterator [A] and the grouping function f, which converts the values of A to its B-groups. The function returns a HashMap for each group B, counts the number of A values that fall into the group.
I use both of these functions to help me with charFreq, a function that uses both apply and groupFreq, to pass a HashMap that counts how many times Char appears in the whole file. If Char is not displayed anywhere in the file, then there should not be a match for it.
def charFreq(file: String): HashMap[Char, Int] =
{
var it = Iterator[Char]()
val words = apply(file)
for {
xs<-words
} yield { it = it ++ xs.toIterator }
val chars = it
val grouper = (x: Char) => x
groupFreq(chars, grouper)
}
, groupFreq , charFreq,
charFreq : java.util.NoSuchElementException: key not : d
, - , , for yield, , , .
Google StackOverflow , .
. , , apply, groupFreq charFreq , , .