user3243499
user3243499

Reputation: 3161

Why this foldLeft scala code does not work?

The following codesnippet is upposed to get me a hash map of Map[String, (String, Int)].

def genList(xx: String) = {
    Seq("one", "two", "three", "four")
}

val oriwords = Set("hello", "how", "are", "you")
val newMap = (Map[String, (String, Int)]() /: oriwords) (
    (cmap, currentWord) => {
        val xv = 2

        genList(currentWord).map(ps => {
            val src = cmap get ps

            if(src == None) {
                cmap + (ps -> (w, xv))
            }
            else {
                if(src.get._2 < xv) {
                    cmap + (ps -> (w, xv))
                }
                else cmap
            }

        })
    }
)

But I am getting the following error:

error: too many arguments for method ->: (y: B)(String, B)
                       cmap + (ps -> (w, xv))
                                  ^

Update: With the suggested changes that are mentioned in the answers, the above error is removed.

val newMap = (Map[String, (String, Int)]() /: oriwords) (
    (cmap, currentWord) => {
        val xv = 2

        genList(currentWord).map(ps => {
            val src = cmap get ps

            if(src == None) {
                cmap + (ps -> ((currentWord, xv)))
            }
            else {
                if(src.get._2 < xv) {
                    cmap + (ps -> ((currentWord, xv)))
                }
                else cmap
            }

        })
    }
)

But now getting a new error on the above code as follows:

error: type mismatch;
 found   : Seq[scala.collection.immutable.Map[String,(String, Int)]]
 required: scala.collection.immutable.Map[String,(String, Int)]
               genList(currentWord).map(ps => {
                                       ^

Upvotes: 0

Views: 249

Answers (2)

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369614

ps -> (w, xv)

is interpreted as

ps.->(w, xv)

i.e. as passing two arguments instead of what you intend, which is passing a 2-tuple as single argument:

ps.->((w, xv))

or in operator syntax:

ps -> ((w, xv))

Upvotes: 2

G&#225;bor Bakos
G&#225;bor Bakos

Reputation: 9100

You need to add an extra parenthesis as the single parenthesis is interpreted as method application:

cmap + (ps -> ((w, xv)))

which means:

cmap + (ps.->((w, xv)))

Or you can use the -> twice:

cmap + (ps -> (w -> xv))

Upvotes: 1

Related Questions