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 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.