我正在斯卡拉做scala课程。我正在经历第6周的任务。我创建了一个函数来查找单词中出现的字符。测试方法在预期结果序列方面失败。斯卡拉coursera分配方法失败测试
下面是问题描述:
/** A word is simply a `String`. */
type Word = String
/** Converts the word into its character occurrence list.
*
* Note: the uppercase and lowercase version of the character are treated as the
* same character, and are represented as a lowercase character in the occurrence list.
*
* Note: you must use `groupBy` to implement this method!
*/
def wordOccurrences(w: Word): Occurrences = {
def breakWord(s: List[Char], xs: List[(Char, Int)]): List[(Char, Int)] = s match {
case Nil => xs
case char :: rest => breakWord(s.tail, matchTuple(xs, char))
}
breakWord(w.toList, List[(Char, Int)]())
}
def matchTuple(tupleList: List[(Char, Int)], char: Char): List[(Char, Int)] = tupleList match {
case Nil => tupleList:+ (char.toLower, 1)
case pair :: restOfList => {
if(pair._1.toLower == char.toLower)
restOfList :+(pair._1, pair._2+1)
else
tupleList:+ (char.toLower, 1)
}
}
可有人请指出我在做什么错。我不需要一个直接的答案,只是逻辑提示我的序列出了什么问题。下面是测试及其结果:
assert(wordOccurrences("Robert") === List(('b', 1), ('e', 1), ('o', 1), ('r', 2), ('t', 1)))
这里是输出:
[info] - wordOccurrences: Robert *** FAILED ***
[info] List((o,1), (b,1), (e,1), (r,2), (t,1)) did not equal List((b,1), (e,1), (o,1), (r,2), (t,1)) (AnagramsSuite.scala:20)
更新: 重构我的功能:
def wordOccurrences(w: Word): Occurrences = {
def breakWord(s: List[Char], xs: List[(Char, Int)]): List[(Char, Int)] = s match {
case Nil => xs
case char :: rest => breakWord(s.tail, xs:+ (char, 1))
}
breakWord(w.toList, List[(Char, Int)]()).groupBy(pair => pair._1.toLower)
.map(entry => (entry._1.toLower, (entry._1.toLower, entry._2.size)))
.values.toList.sorted
}
它看起来太糟糕了,但我将努力进一步改进此方法。
你指示(指令!)使用的'groupBy'在哪里? – jwvh
没有得到如何调用它。将研究如何在这里使用它。 – kromastorm
我推荐它。这可以用1行代码来解决。 'groupBy'是一个小而重要的部分。 – jwvh