diff --git a/core/src/main/scala/cats/data/NonEmptyList.scala b/core/src/main/scala/cats/data/NonEmptyList.scala index 02d1d5f245..5c82e9754c 100644 --- a/core/src/main/scala/cats/data/NonEmptyList.scala +++ b/core/src/main/scala/cats/data/NonEmptyList.scala @@ -165,6 +165,27 @@ final case class NonEmptyList[A](head: A, tail: List[A]) { go(head, tail, Nil) } + /** + * Zips each element of this `NonEmptyList` with its index. + * + * {{{ + * scala> import cats.data.NonEmptyList + * scala> val nel = NonEmptyList.of("a", "b", "c") + * scala> nel.zipWithIndex + * res0: cats.data.NonEmptyList[(String, Int)] = NonEmptyList((a,0), (b,1), (c,2)) + * }}} + */ + def zipWithIndex: NonEmptyList[(A, Int)] = { + val bldr = List.newBuilder[(A, Int)] + var idx = 1 + val it = tail.iterator + while (it.hasNext) { + bldr += ((it.next, idx)) + idx += 1 + } + NonEmptyList((head, 0), bldr.result) + } + } object NonEmptyList extends NonEmptyListInstances { diff --git a/tests/src/test/scala/cats/tests/NonEmptyListTests.scala b/tests/src/test/scala/cats/tests/NonEmptyListTests.scala index 60ce494ae3..98e27f9073 100644 --- a/tests/src/test/scala/cats/tests/NonEmptyListTests.scala +++ b/tests/src/test/scala/cats/tests/NonEmptyListTests.scala @@ -218,6 +218,12 @@ class NonEmptyListTests extends CatsSuite { nel.reverse.toList should === (nel.toList.reverse) } } + + test("NonEmptyList#zipWithIndex is consistent with List#zipWithIndex") { + forAll { nel: NonEmptyList[Int] => + nel.zipWithIndex.toList should === (nel.toList.zipWithIndex) + } + } } class ReducibleNonEmptyListCheck extends ReducibleCheck[NonEmptyList]("NonEmptyList") {