Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add NonEmptyList#toNes (issue #2346) #2557

Merged
merged 6 commits into from
Oct 24, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions core/src/main/scala/cats/data/NonEmptyList.scala
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,19 @@ final case class NonEmptyList[+A](head: A, tail: List[A]) {
*/
def toNem[T, U](implicit ev: A <:< (T, U), order: Order[T]): NonEmptyMap[T, U] =
NonEmptyMap.fromMapUnsafe(SortedMap(toList.map(ev): _*)(order.toOrdering))

/**
* Creates new `NonEmptySet`, similarly to List#toSet from scala standard library.
*{{{
* scala> import cats.data._
* scala> import cats.instances.int._
* scala> val nel = NonEmptyList(1, List(2,2,3,4))
* scala> nel.toNes
* res0: cats.data.NonEmptySet[Int] = TreeSet(1, 2, 3, 4)
*}}}
*/
def toNes[B >: A](implicit order: Order[B]): NonEmptySet[B] =
NonEmptySet.of(head, tail: _*)
}

object NonEmptyList extends NonEmptyListInstances {
Expand Down
9 changes: 8 additions & 1 deletion tests/src/test/scala/cats/tests/NonEmptyListSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package tests

import cats.kernel.laws.discipline.{EqTests, OrderTests, PartialOrderTests, SemigroupTests}

import cats.data.{NonEmptyList, NonEmptyMap, NonEmptyVector}
import cats.data.{NonEmptyList, NonEmptyMap, NonEmptySet, NonEmptyVector}
import cats.data.NonEmptyList.ZipNonEmptyList
import cats.laws.discipline.arbitrary._
import cats.laws.discipline.{
Expand All @@ -15,6 +15,7 @@ import cats.laws.discipline.{
SerializableTests
}
import scala.collection.immutable.SortedMap
import scala.collection.immutable.SortedSet

class NonEmptyListSuite extends CatsSuite {
// Lots of collections here.. telling ScalaCheck to calm down a bit
Expand Down Expand Up @@ -329,6 +330,12 @@ class NonEmptyListSuite extends CatsSuite {
nel.toNem should ===(NonEmptyMap.fromMapUnsafe(SortedMap.empty[Int, String] ++ nel.toList.toMap))
}
}

test("NonEmptyList#toNes is consistent with List#toSet and creating NonEmptySet from it") {
forAll { nel: NonEmptyList[Int] =>
nel.toNes should ===(NonEmptySet.fromSetUnsafe(SortedSet.empty[Int] ++ nel.toList.toSet))
}
}
}

@deprecated("to be able to test deprecated methods", since = "1.0.0-RC1")
Expand Down