Scala / Cats:如何解压缩 NonEmptyList
Scala / Cats: How to unzip an NonEmptyList
标准库在 List
:
上提供 unzip
方法
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")
//)
有没有办法从 cats
库在 NonEmptyList
上实现同样的效果:
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"))
//)
您可以简单地调用 nel.toList
并使用标准 l.unzip
,然后对结果使用 NonEmptyList.fromList(unziped_list)
。
编辑:正如@Dylan 所说,您也可以使用.fromListUnsafe
来摆脱该选项。
您不必在一次遍历中完成所有操作,而且通常您甚至不想使用其中的一个部分。我会这样写:
(nel.map(_._1), nel.map(_._2))
这避免了从 NEL 转换回来的尴尬。
标准库在 List
:
unzip
方法
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")
//)
有没有办法从 cats
库在 NonEmptyList
上实现同样的效果:
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"))
//)
您可以简单地调用 nel.toList
并使用标准 l.unzip
,然后对结果使用 NonEmptyList.fromList(unziped_list)
。
编辑:正如@Dylan 所说,您也可以使用.fromListUnsafe
来摆脱该选项。
您不必在一次遍历中完成所有操作,而且通常您甚至不想使用其中的一个部分。我会这样写:
(nel.map(_._1), nel.map(_._2))
这避免了从 NEL 转换回来的尴尬。