Scala HashMap Key Exception Excepted

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 , , .

+4
2

. , groupFreq() w/o a getOrElse().

charFreq(). , /yield charFreq() . , val l = for IDE, l Iterator[Unit].

vars for. for C flatMap/map ( , ). - ( , ).

Iterator[Char] groupFreq():

1 > var it chars :

val chars = for {
    xs<-words
    i<-xs.toIterator
} yield { i }

2 > flatMap words val:

val chars = words.flatMap( s => s )
+1

. , , :

, ( charFreq), . words.toIterator .

, , . :

val mapped = f(x)
if (!(freqMap contains mapped) freqMap(mapped) = 0
freqMap(mapped)+=1   

. , ( Scala , ;))

def charFreq(file:String) = 
    file.toCharArray.groupBy(m=>m).map(m => (m._1,m._2.size))

:

1) toCharArray Char

2) groupBy (m = > m) , Map[Char,Array[Char]], char char .

3) Map[Char,Array[Char]] Map[Char,Int]], map(m => (m._1,m._2.size)), (key- > value), () .

4) ( , MB, ), , , , , :

def charFreq(hugeFile:String) = {
    //create a mutable map, which can be updated when needed
    val mm = scala.collection.mutable.Map[Char,Int]()
    //iterate over the string
    for (m <- hugeFile) { 
        //ensure that our map contains the entry for the given character
        if (! (mm contains m)) mm(m) = 0          
        mm(m) = mm(m)+1 
    }
    //return the result as an immutable map
    mm.toMap
}
+1

Source: https://habr.com/ru/post/1530873/


All Articles