[英]Scala: filtering list of tuples to get a nonEmptyList
我有一個類型為List[(A, List[B])]
。 我想弄平這個結構並得到:
NonEmptyList[A]
由所有的A
對應於一個非空的List[B]
所有這些B
組合: NonEmptyList[B]
即,我想獲得Option[(NonEmptyList[A], NonEmptyList[B])]
。 什么是最簡潔的方法。
未經測試,但是使用注釋中的定義,這應該可以工作:
for {
a <- NonEmptyList.fromList(list.collect{ case (a, _::_) => a })
b <- NonEmptyList.fromList(list.flatMap(_._2))
} yield (a, b)
如果第一個返回None
這還具有避免第二個計算的優點。
之前的版本:
val listA = list.collect{ case (a, _::_) => a }
val listB = list.flatMap(_._2)
listA.headOption.flatMap(listB.headOption.map(_ => (NonEmptyList(listA), NonEmptyList(listB))))
另一個版本可能是
(listA, listB) match {
case (_::_, _::_) =>
Some(NonEmptyList(listA), NonEmptyList(listB))
case _ =>
None
}
您可以使用尾遞歸函數在列表上進行迭代,但這可能不是很簡潔,但是它可能比第二種解決方案要快,因為它只對列表進行了一次迭代。
def flat[A,B](list: List[(A, List[B])]): Option[(NonEmptyList[A], NonEmptyList[B])] = {
@tailrec
def collapse(list: List[(A, List[B])], as: List[A], bs: List[B]): (List[A], List[B]) = {
list match {
case (a,b) :: xs => collapse(xs, a :: as, b ++ bs)
case Nil => (as, bs)
}
}
collapse(list, Nil, Nil) match {
case (a :: ax, b :: bx) => Some((NonEmptyList(a, ax), NonEmptyList(b, bx)))
case _ => None
}
}
另一種選擇是使用unzip
:
def flat2[A,B](list: List[(A, List[B])]) = list.unzip match {
case (as,bs) => (as, bs.flatten) match {
case (a :: ax, b :: bx) => Some((NonEmptyList(a, ax), NonEmptyList(b, bx)))
case _ => None
}
}
結果:
flat(List((1, List("a", "b")), (2, List("a", "c")), (3, List("d", "e")), (4, List("x", "y"))))
//Some((NonEmptyList(4, 3, 2, 1),NonEmptyList(x, y, d, e, a, c, a, b)))
flat(List((1, List()), (2, List("a"))))
//Some((NonEmptyList(2, 1),NonEmptyList(a)))
flat(List((1, List()), (2, List())))
//None
flat(List())
//None
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.