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 NonEmptyList.zipWithIndex #1517

Merged
merged 2 commits into from
Jan 5, 2017
Merged
Show file tree
Hide file tree
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
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