Skip to content

Commit

Permalink
add SeqOps#concatNeSeq
Browse files Browse the repository at this point in the history
  • Loading branch information
satorg committed Sep 23, 2021
1 parent e865609 commit b0ea384
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
32 changes: 32 additions & 0 deletions core/src/main/scala/cats/syntax/seq.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,37 @@ trait SeqSyntax {
}

final class SeqOps[A](private val va: Seq[A]) extends AnyVal {

/**
* Returns an `Option` of `NonEmptySeq` from a `Seq`
*
* Example:
* {{{
* scala> import cats.data.NonEmptySeq
* scala> import cats.implicits._
*
* scala> val result1: Seq[Int] = Seq(1, 2)
* scala> result1.toNeSeq
* res0: Option[NonEmptySeq[Int]] = Some(NonEmptySeq(1, 2))
*
* scala> val result2: Seq[Int] = Seq.empty[Int]
* scala> result2.toNeSeq
* res1: Option[NonEmptySeq[Int]] = None
* }}}
*/
def toNeSeq: Option[NonEmptySeq[A]] = NonEmptySeq.fromSeq(va)

/**
* Concatenates this `Seq` with a `NonEmptySeq` producing a new `NonEmptySeq`.
*
* Example:
* {{{
* scala> import cats.data.NonEmptySeq
* scala> import cats.implicits._
*
* scala> Seq(1, 2, 3).concatNeSeq(NonEmptySeq.of(4, 5, 6))
* res0: NonEmptySeq[Int] = NonEmptySeq(1, 2, 3, 4, 5, 6)
* }}}
*/
def concatNeSeq[AA >: A](neseq: NonEmptySeq[AA]): NonEmptySeq[AA] = neseq.prependSeq(va)
}
7 changes: 7 additions & 0 deletions tests/src/test/scala/cats/tests/SeqSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ class SeqSuite extends CatsSuite {
assert(Seq.empty[Int].toNeSeq == None)
}

test("concatNeSeq should be consistent with Seq#`++`") {
forAll { (fa: Seq[Int], neseq: NonEmptySeq[Int]) =>
// Note: Scala 2.12.x does not have `Seq#concat`.
assert(fa.concatNeSeq(neseq).toSeq === (fa ++ neseq.toSeq))
}
}

test("traverse is stack-safe") {
val seq = (0 until 100000).toSeq
val sumAll = Traverse[Seq]
Expand Down

0 comments on commit b0ea384

Please sign in to comment.