[英]Scala / Cats: How to unzip an NonEmptyList
The standard library offers the unzip
method on List
:标准库在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")
//)
Is there a way to achieve the same on NonEmptyList
from the cats
library:有没有办法在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"))
//)
You could simply call nel.toList
and use the standard l.unzip
and then NonEmptyList.fromList(unziped_list)
on the result. 你可以简单地调用nel.toList
并在结果上使用标准的l.unzip
然后使用NonEmptyList.fromList(unziped_list)
。
Edit : As @Dylan said, you could also use .fromListUnsafe
to get rid of the option. 编辑 :正如@Dylan所说,你也可以使用.fromListUnsafe
来摆脱选项。
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. 这避免了从NEL返回的尴尬转换。
The unzip
method is available for NonEmptyList
if you import cats.syntax.functor._
.如果您导入cats.syntax.functor._
, unzip
方法可用于NonEmptyList
。
scala> import cats.data.NonEmptyList
scala> import cats.syntax.functor._
scala> val nel = NonEmptyList.of((1, "one"), (2, "two"), (3, "three"), (4, "four"))
val nel: cats.data.NonEmptyList[(Int, String)] = NonEmptyList((1,one), (2,two), (3,three), (4,four))
scala> nel.unzip
val res0: (cats.data.NonEmptyList[Int], cats.data.NonEmptyList[String]) = (NonEmptyList(1, 2, 3, 4),NonEmptyList(one, two, three, four))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.