[英]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返回的尷尬轉換。
如果您導入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.