Skip to content

Commit

Permalink
Implement NonEmptyList#collect (#1516) (#1516)
Browse files Browse the repository at this point in the history
  • Loading branch information
Xavier Fernández Salas authored and kailuowang committed Mar 22, 2017
1 parent df0b9ab commit ec623e4
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
24 changes: 24 additions & 0 deletions core/src/main/scala/cats/data/NonEmptyList.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down
7 changes: 7 additions & 0 deletions tests/src/test/scala/cats/tests/NonEmptyListTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit ec623e4

Please sign in to comment.