我正在斯卡拉做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