Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7803417
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T01:34:42+00:00 2026-06-02T01:34:42+00:00

I am trying to implement a simple wordcount in scala using an immutable map(this

  • 0

I am trying to implement a simple wordcount in scala using an immutable map(this is intentional) and the way I am trying to accomplish it is as follows:

  1. Create an empty immutable map
  2. Create a scanner that reads through the file.
  3. While the scanner.hasNext() is true:

    • Check if the Map contains the word, if it doesn’t contain the word, initialize the count to zero
    • Create a new entry with the key=word and the value=count+1
    • Update the map
  4. At the end of the iteration, the map is populated with all the values.

My code is as follows:

val wordMap = Map.empty[String,Int]
val input = new java.util.scanner(new java.io.File("textfile.txt"))
while(input.hasNext()){
  val token = input.next()
  val currentCount = wordMap.getOrElse(token,0) + 1
  val wordMap = wordMap + (token,currentCount)
}

The ides is that wordMap will have all the wordCounts at the end of the iteration…
Whenever I try to run this snippet, I get the following exception

recursive value wordMap needs type.

Can somebody point out why I am getting this exception and what can I do to remedy it?

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T01:34:43+00:00Added an answer on June 2, 2026 at 1:34 am
    val wordMap = wordMap + (token,currentCount)
    

    This line is redefining an already-defined variable. If you want to do this, you need to define wordMap with var and then just use

    wordMap = wordMap + (token,currentCount)
    

    Though how about this instead?:

    io.Source.fromFile("textfile.txt")            // read from the file
      .getLines.flatMap{ line =>                  // for each line
         line.split("\\s+")                       // split the line into tokens
           .groupBy(identity).mapValues(_.size)   // count each token in the line
      }                                           // this produces an iterator of token counts
      .toStream                                   // make a Stream so we can groupBy
      .groupBy(_._1).mapValues(_.map(_._2).sum)   // combine all the per-line counts
      .toList
    

    Note that the per-line pre-aggregation is used to try and reduce the memory required. Counting across the entire file at once might be too big.

    If your file is really massive, I would suggest using doing this in parallel (since word counting is trivial to parallelize) using either Scala’s parallel collections or Hadoop (using one of the cool Scala Hadoop wrappers like Scrunch or Scoobi).

    EDIT: Detailed explanation:

    Ok, first look at the inner part of the flatMap. We take a string, and split it apart on whitespace:

    val line = "a b c b"
    val tokens = line.split("\\s+") // Array(a, b, c, a, b)
    

    Now identity is a function that just returns its argument, so if wegroupBy(identity)`, we map each distinct word type, to each word token:

    val grouped = tokens.groupBy(identity) // Map(c -> Array(c), a -> Array(a), b -> Array(b, b))
    

    And finally, we want to count up the number of tokens for each type:

    val counts = grouped.mapValues(_.size) // Map(c -> 1, a -> 1, b -> 2)
    

    Since we map this over all the lines in the file, we end up with token counts for each line.

    So what does flatMap do? Well, it runs the token-counting function over each line, and then combines all the results into one big collection.

    Assume the file is:

    a b c b
    b c d d d
    e f c
    

    Then we get:

    val countsByLine = 
      io.Source.fromFile("textfile.txt")            // read from the file
        .getLines.flatMap{ line =>                  // for each line
           line.split("\\s+")                       // split the line into tokens
             .groupBy(identity).mapValues(_.size)   // count each token in the line
        }                                           // this produces an iterator of token counts
    println(countsByLine.toList) // List((c,1), (a,1), (b,2), (c,1), (d,3), (b,1), (c,1), (e,1), (f,1))
    

    So now we need to combine the counts of each line into one big set of counts. The countsByLine variable is an Iterator, so it doesn’t have a groupBy method. Instead we can convert it to a Stream, which is basically a lazy list. We want laziness because we don’t want to have to read the entire file into memory before we start. Then the groupBy groups all counts of the same word type together.

    val groupedCounts = countsByLine.toStream.groupBy(_._1)
    println(groupedCounts.mapValues(_.toList)) // Map(e -> List((e,1)), f -> List((f,1)), a -> List((a,1)), b -> List((b,2), (b,1)), c -> List((c,1), (c,1), (c,1)), d -> List((d,3)))
    

    And finally we can sum up the counts from each line for each word type by grabbing the second item from each tuple (the count), and summing:

    val totalCounts = groupedCounts.mapValues(_.map(_._2).sum)
    println(totalCounts.toList)
    List((e,1), (f,1), (a,1), (b,3), (c,3), (d,3))
    

    And there you have it.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to implement this simple example of how to synchronize threads using pthread
I've been trying to implement simple low level keyhook using JNI and all went
Iam trying to implement a simple JMS(traditional not using springs) code in eclipse using
I am trying to implement a simple request to Wikipedia's API using AJAX (XMLHttpRequest).
im trying to implement simple secured client server communiction using WCF. when im launching
I am trying to implement simple xhr abstraction, and am getting this warning when
I am trying to implement a simple Observer pattern using .net Observable class. I
I am trying to implement simple chat application using flex. In it all my
I'm trying to implement Simple chat using Servlet 3.0 and Comet pattern based on
I'm trying to implement simple inverse kinematics test using OpenGL, Eigen3 and Jacobian pseudoinverse

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.