我在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