Skip to content

Commit be4a99d

Browse files
authored
Merge pull request #4844 from loladenney/main
Added doctests for map, collectFirst, foldLeft, and foldRight for NonEmptyList
2 parents 907a34f + 7e6a3a2 commit be4a99d

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

core/src/main/scala/cats/data/NonEmptyList.scala

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,13 @@ final case class NonEmptyList[+A](head: A, tail: List[A]) extends NonEmptyCollec
104104

105105
/**
106106
* Applies f to all the elements of the structure
107+
*
108+
* {{{
109+
* scala> import cats.data.NonEmptyList
110+
* scala> val nel = NonEmptyList.of(1, 2, 3, 4, 5)
111+
* scala> nel.map(_ * 10)
112+
* res0: cats.data.NonEmptyList[Int] = NonEmptyList(10, 20, 30, 40, 50)
113+
* }}}
107114
*/
108115
def map[B](f: A => B): NonEmptyList[B] =
109116
NonEmptyList(f(head), tail.map(f))
@@ -263,6 +270,15 @@ final case class NonEmptyList[+A](head: A, tail: List[A]) extends NonEmptyCollec
263270

264271
/**
265272
* Find the first element matching the partial function, if one exists
273+
*
274+
* {{{
275+
* scala> import cats.data.NonEmptyList
276+
* scala> val nel = NonEmptyList.of(2, 4, 6, 8, 10)
277+
* scala> nel.collectFirst { case v if v > 5 => v }
278+
* res0: Option[Int] = Some(6)
279+
* scala> nel.collectFirst { case v if v % 2 == 1 => "odd" }
280+
* res1: Option[String] = None
281+
* }}}
266282
*/
267283
def collectFirst[B](pf: PartialFunction[A, B]): Option[B] =
268284
if (pf.isDefinedAt(head)) {
@@ -308,12 +324,24 @@ final case class NonEmptyList[+A](head: A, tail: List[A]) extends NonEmptyCollec
308324

309325
/**
310326
* Left-associative fold on the structure using f.
327+
* {{{
328+
* scala> import cats.data.NonEmptyList
329+
* scala> val nel = NonEmptyList.of(1, 2, 3, 4, 5)
330+
* scala> nel.foldLeft (0) ((a, b) => a + b)
331+
* res0: Int = 15
332+
* }}}
311333
*/
312334
def foldLeft[B](b: B)(f: (B, A) => B): B =
313335
tail.foldLeft(f(b, head))(f)
314336

315337
/**
316338
* Right-associative fold on the structure using f.
339+
* scala> import cats.data.NonEmptyList
340+
* scala> import cats.Eval
341+
* scala> import scala.math.pow
342+
* scala> val nel = NonEmptyList.of(2,2,2)
343+
* scala> (nel.foldRight (Eval.now(1)) ((a, b) => Eval.now(pow(a, b.value).toInt))).value
344+
* res0: Int = 16
317345
*/
318346
def foldRight[B](lb: Eval[B])(f: (A, Eval[B]) => Eval[B]): Eval[B] =
319347
Foldable[List].foldRight(toList, lb)(f)

0 commit comments

Comments
 (0)