首页 > 解决方案 > Scala / Cats:如何解压缩 NonEmptyList

问题描述

标准库提供了unzipon 的方法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")
//)

有没有办法NonEmptyListcats图书馆实现同样的目标:

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"))
//)

标签: scalascala-cats

解决方案


您可以简单地调用nel.toList并使用标准l.unzip,然后NonEmptyList.fromList(unziped_list)使用结果。

编辑:正如@Dylan 所说,您也可以使用.fromListUnsafe来摆脱该选项。


推荐阅读