Skip to content

Commit

Permalink
Merge pull request #2956 from kailuowang/takeWhile
Browse files Browse the repository at this point in the history
added Chain#takeWhile and Chain#dropWhile
  • Loading branch information
djspiewak authored Jul 23, 2019
2 parents c313eb0 + 2e3960f commit 374a93b
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
34 changes: 34 additions & 0 deletions core/src/main/scala/cats/data/Chain.scala
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,40 @@ sealed abstract class Chain[+A] {
result
}

/**
* Takes longest prefix of elements that satisfy a predicate.
* @param p The predicate used to test elements.
* @return the longest prefix of this chain whose elements all satisfy the predicate p.
*/
final def takeWhile(p: A => Boolean): Chain[A] = {
var result = Chain.empty[A]
foreachUntil { a =>
val pr = p(a)
if (pr) result = result :+ a
!pr
}
result
}

/**
* Drops longest prefix of elements that satisfy a predicate.
*
* @param p The predicate used to test elements.
* @return the longest suffix of this sequence whose first element does not satisfy the predicate p.
*/
final def dropWhile(p: A => Boolean): Chain[A] = {
@tailrec
def go(rem: Chain[A]): Chain[A] =
rem.uncons match {
case Some((a, tail)) =>
if (p(a)) go(tail)
else rem

case None => nil
}
go(this)
}

/**
* Folds over the elements from right to left using the supplied initial value and function.
*/
Expand Down
13 changes: 13 additions & 0 deletions tests/src/test/scala/cats/tests/ChainSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -224,4 +224,17 @@ class ChainSuite extends CatsSuite {
x.hashCode should ===(x.toList.hashCode)
}
}

test("Chain#takeWhile is consistent with List#takeWhile") {
forAll { (x: Chain[Int], p: Int => Boolean) =>
x.takeWhile(p).toList should ===(x.toList.takeWhile(p))
}
}

test("Chain#dropWhile is consistent with List#dropWhile") {
forAll { (x: Chain[Int], p: Int => Boolean) =>
x.dropWhile(p).toList should ===(x.toList.dropWhile(p))
}
}

}

0 comments on commit 374a93b

Please sign in to comment.