简体   繁体   中英

Scala / Cats: How to unzip an NonEmptyList

The standard library offers the unzip method on List :


scala>val l = List((1, "one"), (2, "two"), (3, "three"), (4, "four"), (5, "five"))

scala> l.unzip
// res13: (List[Int], List[String]) = (
//  List(1, 2, 3, 4, 5),
//  List("one", "two", "three", "four", "five")
//)

Is there a way to achieve the same on NonEmptyList from the cats library:

scala> import cats.data.NonEmptyList

scala> val nel = NonEmptyList.of((1, "one"), (2, "two"), (3, "three"), (4, "four"), (5, "five"))
//res15: NonEmptyList[(Int, String)] = NonEmptyList(
//  (1, "one"),
//  List((2, "two"), (3, "three"), (4, "four"), (5, "five"))
//)

You could simply call nel.toList and use the standard l.unzip and then NonEmptyList.fromList(unziped_list) on the result.

Edit : As @Dylan said, you could also use .fromListUnsafe to get rid of the option.

You don't have to do it all in one traversal, and often you don't even want to use one of the parts. I would write it like:

(nel.map(_._1), nel.map(_._2))

This avoids the awkward conversion away from an NEL and back.

The unzip method is available for NonEmptyList if you import cats.syntax.functor._ .

scala> import cats.data.NonEmptyList
                                                                             
scala> import cats.syntax.functor._
                                                                             
scala> val nel = NonEmptyList.of((1, "one"), (2, "two"), (3, "three"), (4, "four"))
val nel: cats.data.NonEmptyList[(Int, String)] = NonEmptyList((1,one), (2,two), (3,three), (4,four))
                                                                             
scala> nel.unzip
val res0: (cats.data.NonEmptyList[Int], cats.data.NonEmptyList[String]) = (NonEmptyList(1, 2, 3, 4),NonEmptyList(one, two, three, four))

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