【发布时间】:2017-03-02 16:33:21
【问题描述】:
我正在编写一个函数,它将获取字符串中出现的字符 (List[(Char, Int)]) 的列表,并生成该出现列表的所有子集。
所以,给定
List(('a', 2), ('b', 2))
它会产生
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))
)
我是这样实现的:
type Occurrences = List[(Char, Int)]
def combinations(occurrences: Occurrences): List[Occurrences] =
if (occurrences.isEmpty) List(List())
else for {
(c, n) <- occurrences
i <- n to 1 by -1
} yield (c, i) :: combinations(occurrences.tail)
我得到这个错误:
type mismatch;
found : List[List[Product with Serializable]]
required: List[Occurrences]
(which expands to) List[List[(Char, Int)]]
请帮助我理解,为什么会发生这种情况,我该如何解决?
我尝试将其重写为 flatMap...,使用 Intellij 的“解释 Scala 代码”等。
【问题讨论】:
-
有什么特殊原因阻止您接受答案?
标签: scala types yield for-comprehension