简体   繁体   中英

Scala: filtering list of tuples to get a nonEmptyList

I have a list of the type List[(A, List[B])] . I want to flatten this structure and get:

  • NonEmptyList[A] consisting of all the A corresponding to a nonEmpty List[B] .

  • all those B s combined: NonEmptyList[B]

ie, I want to get Option[(NonEmptyList[A], NonEmptyList[B])] . What is the most concise way of doing this.

Untested, but using definitions from the comments, this should work:

for {
  a <- NonEmptyList.fromList(list.collect{ case (a, _::_) => a })
  b <- NonEmptyList.fromList(list.flatMap(_._2))
} yield (a, b)

This also has the advantage of avoiding the second computation if the first returns None .


Previous versions:

val listA = list.collect{ case (a, _::_) => a }
val listB = list.flatMap(_._2)

listA.headOption.flatMap(listB.headOption.map(_ => (NonEmptyList(listA), NonEmptyList(listB))))

Another version might be

(listA, listB) match {
  case (_::_, _::_) =>
    Some(NonEmptyList(listA), NonEmptyList(listB))
  case _ =>
    None
}

You could just iterate over the list with tail-recursive function, but it's probably not very concise, but it might be faster than the second solution because it iterates just once over the list.

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
    }

}

Another option is to use 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
   }
}

Result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM