标准库提供以下unzip方法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")
//)
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以NonEmptyList从cats库中实现相同目的:
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"))
//)
Run Code Online (Sandbox Code Playgroud)
您可以简单地调用nel.toList并使用该标准l.unzip,然后NonEmptyList.fromList(unziped_list)得出结果。
编辑:正如@Dylan所说,你也可以用来.fromListUnsafe摆脱这个选项。
您不必在一次遍历中完成所有操作,而且通常您甚至不想使用其中的一个部分。我会这样写:
(nel.map(_._1), nel.map(_._2))
Run Code Online (Sandbox Code Playgroud)
这避免了与 NEL 之间的尴尬转换。