From 2244f7f4b55dd9c421745c797c39c97292892ceb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Gutowski?= Date: Sat, 29 Sep 2018 17:00:56 +0200 Subject: [PATCH] Add NonEmptyList#toNem (issue #2346) --- core/src/main/scala/cats/data/NonEmptyList.scala | 15 +++++++++++++++ .../test/scala/cats/tests/NonEmptyListSuite.scala | 9 ++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/core/src/main/scala/cats/data/NonEmptyList.scala b/core/src/main/scala/cats/data/NonEmptyList.scala index eadde0ced5..15315d7f38 100644 --- a/core/src/main/scala/cats/data/NonEmptyList.scala +++ b/core/src/main/scala/cats/data/NonEmptyList.scala @@ -406,6 +406,21 @@ final case class NonEmptyList[+A](head: A, tail: List[A]) { */ def groupByNem[B](f: A => B)(implicit B: Order[B]): NonEmptyMap[B, NonEmptyList[A]] = NonEmptyMap.fromMapUnsafe(groupBy(f)) + + + /** + * Creates new `NonEmptyMap`, similarly to List#toMap from scala standard library. + *{{{ + * scala> import cats.data._ + * scala> import cats.instances.int._ + * scala> val nel = NonEmptyList((0, "a"), List((1, "b"),(0, "c"), (2, "d"))) + * scala> nel.toNem + * res0: NonEmptyMap[Int,String] = Map(0 -> c, 1 -> b, 2 -> d) + *}}} + * + */ + def toNem[T, U](implicit ev: A <:< (T, U), order: Order[T]): NonEmptyMap[T, U] = + NonEmptyMap.fromMapUnsafe(SortedMap(toList.map(ev): _*)(order.toOrdering)) } object NonEmptyList extends NonEmptyListInstances { diff --git a/tests/src/test/scala/cats/tests/NonEmptyListSuite.scala b/tests/src/test/scala/cats/tests/NonEmptyListSuite.scala index ffc184a220..948dac307c 100644 --- a/tests/src/test/scala/cats/tests/NonEmptyListSuite.scala +++ b/tests/src/test/scala/cats/tests/NonEmptyListSuite.scala @@ -3,10 +3,11 @@ package tests import cats.kernel.laws.discipline.{SemigroupTests, OrderTests, PartialOrderTests, EqTests} -import cats.data.{NonEmptyList, NonEmptyVector} +import cats.data.{NonEmptyList, NonEmptyVector, NonEmptyMap} import cats.data.NonEmptyList.ZipNonEmptyList import cats.laws.discipline.arbitrary._ import cats.laws.discipline.{CommutativeApplyTests, BimonadTests, NonEmptyTraverseTests, ReducibleTests, SemigroupKTests, SerializableTests} +import scala.collection.immutable.SortedMap class NonEmptyListSuite extends CatsSuite { // Lots of collections here.. telling ScalaCheck to calm down a bit @@ -315,6 +316,12 @@ class NonEmptyListSuite extends CatsSuite { ior.right.map(xs => xs.sorted should === (xs)) } } + + test("NonEmptyList#toNem is consistent with List#toMap and creating NonEmptyMap from it") { + forAll { nel: NonEmptyList[(Int, String)] => + nel.toNem should ===(NonEmptyMap.fromMapUnsafe(SortedMap.empty[Int, String] ++ nel.toList.toMap)) + } + } } @deprecated("to be able to test deprecated methods", since = "1.0.0-RC1")