undisp
undisp

Reputation: 721

Scala function doesn't return the desired result

I have a function that (supposedly) returns a List(String, Int) that tells the number of times that a word appears in a string, for example:

"This is a sample string like every other sample string"

The list should have this:

List[(String, Int)] = List(("This", 1), ("is", 1), ("a", 1), ("sample", 2), ("string", 2), ...)

However I'm getting this result:

List[(String, Int)] = List((is,1), (a,1), (sample,1), (string,1), (like,1), (every,1), (other,1), (sample,1), (string,1))

The function that I have is this one:

def unConstructList(xs: List[String]): List[(String, Int)] = xs match {
    case Nil    => Nil
    case x :: s => List((x, xs.takeWhile(y => y == x).length)) ++ unConstructList(xs.dropWhile(z => z == x))
  } 

Does anyone know what am I doing wrong?

Upvotes: 0

Views: 47

Answers (1)

Tzach Zohar
Tzach Zohar

Reputation: 37852

takeWhile stops on the first element that doesn't satisfy the predicate you're passing. From its Scaladoc:

Takes longest prefix of elements that satisfy a predicate

In this case it means that xs.takeWhile(y => y == x).length will return a value greater than 1 only if x is both the first and the second item on the list, and in your example - no word appears twice consecutively so all words end up with the value 1.

I'll leave it for you to fix...

Upvotes: 3

Related Questions