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

add List#scanLeftNel and List#scanRightNel #3239

Merged
Merged
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
43 changes: 42 additions & 1 deletion core/src/main/scala/cats/syntax/list.scala
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package cats
package syntax

import scala.collection.immutable.SortedMap
import cats.data.{NonEmptyChain, NonEmptyList}

import scala.collection.immutable.SortedMap

trait ListSyntax {
implicit final def catsSyntaxList[A](la: List[A]): ListOps[A] = new ListOps(la)
}
Expand Down Expand Up @@ -50,6 +51,46 @@ final class ListOps[A](private val la: List[A]) extends AnyVal {
implicit val ordering: Ordering[B] = B.toOrdering
toNel.fold(SortedMap.empty[B, NonEmptyList[A]])(_.groupBy(f))
}

/** Produces a `NonEmptyList` containing cumulative results of applying the
* operator going left to right.
*
* Example:
* {{{
* scala> import cats.data.NonEmptyList
* scala> import cats.implicits._
*
* scala> val result1: List[Int] = List(1, 2)
* scala> result1.scanLeftNel(100)(_ + _)
* res0: NonEmptyList[Int] = NonEmptyList(100, 101, 103)
*
* scala> val result2: List[Int] = List.empty[Int]
* scala> result2.scanLeftNel(1)(_ + _)
* res1: NonEmptyList[Int] = NonEmptyList(1)
* }}}
*/
def scanLeftNel[B](b: B)(f: (B, A) => B): NonEmptyList[B] =
NonEmptyList.fromListUnsafe(la.scanLeft(b)(f))

/** Produces a `NonEmptyList` containing cumulative results of applying the
* operator going right to left.
*
* Example:
* {{{
* scala> import cats.data.NonEmptyList
* scala> import cats.implicits._
*
* scala> val result1: List[Int] = List(1, 2)
* scala> result1.scanRightNel(100)(_ + _)
* res0: NonEmptyList[Int] = NonEmptyList(103, 102, 100)
*
* scala> val result2: List[Int] = List.empty[Int]
* scala> result2.scanRightNel(1)(_ + _)
* res1: NonEmptyList[Int] = NonEmptyList(1)
* }}}
*/
def scanRightNel[B](b: B)(f: (A, B) => B): NonEmptyList[B] =
NonEmptyList.fromListUnsafe(la.scanRight(b)(f))
}

private[syntax] trait ListSyntaxBinCompat0 {
Expand Down