Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String Scala函数没有';t返回所需的结果_String_Scala_Function - Fatal编程技术网

String Scala函数没有';t返回所需的结果

String Scala函数没有';t返回所需的结果,string,scala,function,String,Scala,Function,我有一个函数,它(假定)返回一个列表(String,Int),告诉一个单词在字符串中出现的次数,例如: “这是一个与其他示例字符串类似的示例字符串” 该列表应包含以下内容: 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,Int)
,告诉一个单词在字符串中出现的次数,例如:

“这是一个与其他示例字符串类似的示例字符串”

该列表应包含以下内容:

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

有人知道我做错了什么吗?

takeWhile
在不满足您传递的谓词的第一个元素上停止。从其Scaladoc:

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

在这种情况下,这意味着
xs.takeWhile(y=>y==x).length
将返回大于
1
的值,前提是
x
同时是列表中的第一项和第二项,并且在您的示例中,没有单词连续出现两次,因此所有单词都以
1
的值结束


我将把它留给您来修复…

take,同时
在第一个不满足您传递的谓词的元素上停止。从其Scaladoc:

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

在这种情况下,这意味着
xs.takeWhile(y=>y==x).length
将返回大于
1
的值,前提是
x
同时是列表中的第一项和第二项,并且在您的示例中,没有单词连续出现两次,因此所有单词都以
1
的值结束


我将把它留给您来修复…

xs.groupBy(identity).mapValues(u.size).toList
这非常有效。谢谢请把这个作为答案写下来,这样我就可以接受了。
xs.groupBy(identity).mapValues(u.size).toList
这很有效。谢谢请写下这个作为答案,这样我就可以接受了。哦,你说得对。我没有注意到那个错误。谢谢。哦,你说得对。我没有注意到那个错误。谢谢