Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala / Cats: How to unzip an NonEmptyList

The standard library offers the unzip method on 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")
//)

Is there a way to achieve the same on NonEmptyList from the cats library:

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"))
//)
like image 711
Valy Dia Avatar asked Jul 18 '19 16:07

Valy Dia


2 Answers

You could simply call nel.toList and use the standard l.unzip and then NonEmptyList.fromList(unziped_list) on the result.

Edit: As @Dylan said, you could also use .fromListUnsafe to get rid of the option.

like image 103
Arnaud Claudel Avatar answered Sep 30 '22 05:09

Arnaud Claudel


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.

like image 33
Karl Bielefeldt Avatar answered Sep 30 '22 06:09

Karl Bielefeldt