Skip to content

Commit

Permalink
Add NonEmptyList.zipWithIndex (#1517)
Browse files Browse the repository at this point in the history
* Add NonEmptyList.zipWithIndex

* Use builder instead of recursion for performance reasons.
  • Loading branch information
cranst0n authored and johnynek committed Jan 5, 2017
1 parent 39c3e48 commit 468e753
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
21 changes: 21 additions & 0 deletions core/src/main/scala/cats/data/NonEmptyList.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
6 changes: 6 additions & 0 deletions tests/src/test/scala/cats/tests/NonEmptyListTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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") {
Expand Down

0 comments on commit 468e753

Please sign in to comment.