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

Implement NonEmptyList#Collect #1516

Merged
merged 1 commit into from
Mar 22, 2017
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
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