Skip to content

Commit 5c72ffc

Browse files
enziefrossabaker
authored andcommitted
add List#scanLeftNel and List#scanRightNel (#3239)
* add List#scanLeftNel * PR comments * fix doc test
1 parent d2f8a96 commit 5c72ffc

1 file changed

Lines changed: 42 additions & 1 deletion

File tree

core/src/main/scala/cats/syntax/list.scala

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
package cats
22
package syntax
33

4-
import scala.collection.immutable.SortedMap
54
import cats.data.{NonEmptyChain, NonEmptyList}
65

6+
import scala.collection.immutable.SortedMap
7+
78
trait ListSyntax {
89
implicit final def catsSyntaxList[A](la: List[A]): ListOps[A] = new ListOps(la)
910
}
@@ -50,6 +51,46 @@ final class ListOps[A](private val la: List[A]) extends AnyVal {
5051
implicit val ordering: Ordering[B] = B.toOrdering
5152
toNel.fold(SortedMap.empty[B, NonEmptyList[A]])(_.groupBy(f))
5253
}
54+
55+
/** Produces a `NonEmptyList` containing cumulative results of applying the
56+
* operator going left to right.
57+
*
58+
* Example:
59+
* {{{
60+
* scala> import cats.data.NonEmptyList
61+
* scala> import cats.implicits._
62+
*
63+
* scala> val result1: List[Int] = List(1, 2)
64+
* scala> result1.scanLeftNel(100)(_ + _)
65+
* res0: NonEmptyList[Int] = NonEmptyList(100, 101, 103)
66+
*
67+
* scala> val result2: List[Int] = List.empty[Int]
68+
* scala> result2.scanLeftNel(1)(_ + _)
69+
* res1: NonEmptyList[Int] = NonEmptyList(1)
70+
* }}}
71+
*/
72+
def scanLeftNel[B](b: B)(f: (B, A) => B): NonEmptyList[B] =
73+
NonEmptyList.fromListUnsafe(la.scanLeft(b)(f))
74+
75+
/** Produces a `NonEmptyList` containing cumulative results of applying the
76+
* operator going right to left.
77+
*
78+
* Example:
79+
* {{{
80+
* scala> import cats.data.NonEmptyList
81+
* scala> import cats.implicits._
82+
*
83+
* scala> val result1: List[Int] = List(1, 2)
84+
* scala> result1.scanRightNel(100)(_ + _)
85+
* res0: NonEmptyList[Int] = NonEmptyList(103, 102, 100)
86+
*
87+
* scala> val result2: List[Int] = List.empty[Int]
88+
* scala> result2.scanRightNel(1)(_ + _)
89+
* res1: NonEmptyList[Int] = NonEmptyList(1)
90+
* }}}
91+
*/
92+
def scanRightNel[B](b: B)(f: (A, B) => B): NonEmptyList[B] =
93+
NonEmptyList.fromListUnsafe(la.scanRight(b)(f))
5394
}
5495

5596
private[syntax] trait ListSyntaxBinCompat0 {

0 commit comments

Comments
 (0)