Scala函数不会返回所需的结果

时间:2016-04-30 21:42:12

标签: string scala function

我有一个函数(据说)返回一个List(String, Int),它告诉单词出现在字符串中的次数,例如:

  

"这是一个示例字符串,就像其他每个示例字符串一样#34;

列表应该包含:

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

但是我得到了这个结果:

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

我的功能就是这个:

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))
  } 

有谁知道我做错了什么?

1 个答案:

答案 0 :(得分:3)

takeWhile第一个元素上停止,该元素不满足您传递的谓词。来自Scaladoc:

  

获取满足谓词的元素的最长前缀

在这种情况下,只有当xs.takeWhile(y => y == x).length同时是列表中的第一项和第二项时,1才会返回大于x的值,并且在您的示例中 - 否单词连续出现,因此所有单词都以值1结束。

我会留给你修理......