【发布时间】:2016-05-10 10:28:53
【问题描述】:
我有以下对 (key,id) 的列表:
val pairs = List(('a',1), ('a',2), ('b',1), ('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))
)
注意 (List(('a',1),('a',2)) 不应该是输出的一部分,因此不能使用 Scala List.combinations
我目前有以下代码:
def subSeq (xs: List[(Char, Int)]): List[(Char,Int)] = {
xs match {
case Nil => List()
case y::ys => {
val eh = xs.filter (c => c._1 == y._1)
val et = xs.filter (c => c._1 != y._1)
for (z: (Char,Int) <- eh) yield z :: subSeq(et)
}
}
}
但我收到一条错误消息:List[List[(Char,Int)]] does not match List[(Char,Int)]
【问题讨论】:
-
您的返回类型与您提供的输出不符。如果你想要
List(List(), ...作为输出,也许你应该返回List[List[(Char, Int)]]?。还有一个提示:您可以使用list.flatten将List[List[T]]翻译成List[T] -
flatten 确实解决了类型不匹配但产生错误的结果 -
List((a,1), (b,1), (c,1), (b,2), (c,1), (a,2), (b,1), (c,1), (b,2), (c,1))这是对列表而不是组合列表列表
标签: scala for-loop recursion yield