我在coursera上做scala課程。我正在經歷第6周的任務。我堅持組合功能。scala coursera第6周分配方法編譯錯誤
這裏有問題的描述:
type Occurrences = List[(Char, Int)]
/**
* Returns the list of all subsets of the occurrence list.
* This includes the occurrence itself, i.e. `List(('k', 1), ('o', 1))`
* is a subset of `List(('k', 1), ('o', 1))`.
* It also include the empty subset `List()`.
*
* Example: the subsets of the occurrence list `List(('a', 2), ('b', 2))` are:
*
* List(
* List(),
* List(('a', 1)),
* List(('a', 2)),
* List(('b', 1)),
* List(('a', 1), ('b', 1)),
* List(('a', 2), ('b', 1)),
* List(('b', 2)),
* List(('a', 1), ('b', 2)),
* List(('a', 2), ('b', 2))
* )
*
* Note that the order of the occurrence list subsets does not matter -- the subsets
* in the example above could have been displayed in some other order.
*/
def combinations(occurrences: Occurrences): List[Occurrences] =???
這是基於什麼我能理解其中的邏輯我的解決方案:
def combinations(occurences: Occurrences) : List[Occurrences] = {
def restTuplesCombination(occ: Occurrences, xs: List[Occurrences]): List[Occurrences] = occ match {
case Nil=> xs :+ Nil
case head :: rest => {
for(
entry <- headTupleCombination(head)
combination <- restTuplesCombination(rest, xs) // getting error here
) yield if(entry._2 == 0)
combination
else
entry :: combination
// case close
}
}
def headTupleCombination(tuple: (Char, Int)):List[(Char, Int)] = {
if(tuple._2 < 0)
Nil
else
tuple :: headTupleCombination((tuple._1, tuple._2 -1))
}
restTuplesCombination(occurences, Nil)
}
的方法是很長,但它看起來可讀我。我得到的聲明:組合< - restTuplesCombination(其餘,xs)
我不明白什麼是打破代碼在這裏。 for循環中的兩個表達式都返回兩個集合,我使用yield來創建元素的組合。
請讓我知道我在這裏做錯了什麼。
謝謝
謝謝道文。我現在明白這個區別。 – kromastorm