From d0f6f0ba3e91556ffcecb9802221efce52755282 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Xavier=20Fern=C3=83=C2=83=C3=82=C2=A1ndez=20Salas?= Date: Thu, 5 Jan 2017 12:01:06 +0100 Subject: [PATCH] Implement NonEmptyList#collect (#1516) --- .../main/scala/cats/data/NonEmptyList.scala | 24 +++++++++++++++++++ .../scala/cats/tests/NonEmptyListTests.scala | 7 ++++++ 2 files changed, 31 insertions(+) diff --git a/core/src/main/scala/cats/data/NonEmptyList.scala b/core/src/main/scala/cats/data/NonEmptyList.scala index 1031b845cd..60e7333924 100644 --- a/core/src/main/scala/cats/data/NonEmptyList.scala +++ b/core/src/main/scala/cats/data/NonEmptyList.scala @@ -66,6 +66,30 @@ final case class NonEmptyList[+A](head: A, tail: List[A]) { else head :: ftail } + /** + * Builds a new `List` by applying a partial function to + * all the elements from this `NonEmptyList` on which the function is defined + * + * {{{ + * scala> import cats.data.NonEmptyList + * scala> val nel = NonEmptyList.of(1, 2, 3, 4, 5) + * scala> nel.collect { case v if v < 3 => v } + * res0: scala.collection.immutable.List[Int] = List(1, 2) + * scala> nel.collect { + * | case v if v % 2 == 0 => "even" + * | case _ => "odd" + * | } + * res1: scala.collection.immutable.List[String] = List(odd, even, odd, even, odd) + * }}} + */ + def collect[B](pf: PartialFunction[A, B]) : List[B] = { + if (pf.isDefinedAt(head)) { + pf.apply(head) :: tail.collect(pf) + } else { + tail.collect(pf) + } + } + /** * Append another NonEmptyList */ diff --git a/tests/src/test/scala/cats/tests/NonEmptyListTests.scala b/tests/src/test/scala/cats/tests/NonEmptyListTests.scala index 98e27f9073..166a40d53d 100644 --- a/tests/src/test/scala/cats/tests/NonEmptyListTests.scala +++ b/tests/src/test/scala/cats/tests/NonEmptyListTests.scala @@ -88,6 +88,13 @@ class NonEmptyListTests extends CatsSuite { } } + test("NonEmptyList#collect is consistent with List#collect") { + forAll { (nel: NonEmptyList[Int], pf: PartialFunction[Int, String]) => + val list = nel.toList + nel.collect(pf) should === (list.collect(pf)) + } + } + test("NonEmptyList#find is consistent with List#find") { forAll { (nel: NonEmptyList[Int], p: Int => Boolean) => val list = nel.toList