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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With