Skip to content

Commit

Permalink
Add indexed to Traverse
Browse files Browse the repository at this point in the history
  • Loading branch information
andyscott committed Jul 7, 2017
1 parent 099e459 commit eef6979
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
12 changes: 12 additions & 0 deletions core/src/main/scala/cats/Traverse.scala
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package cats

import cats.data.State

import simulacrum.typeclass

/**
Expand Down Expand Up @@ -97,4 +99,14 @@ import simulacrum.typeclass

override def map[A, B](fa: F[A])(f: A => B): F[B] =
traverse[Id, A, B](fa)(f)

/**
* Traverses through the structure F, pairing the values with
* assigned indices.
*
* The behavior is consistent with the Scala collection library's
* `zipWithIndex` for collections such as `List`.
*/
def indexed[A](fa: F[A]): F[(A, Int)] =
traverse(fa)(a => State((s: Int) => (s + 1, (a, s)))).runA(0).value
}
41 changes: 41 additions & 0 deletions tests/src/test/scala/cats/tests/TraverseTests.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package cats
package tests

import org.scalatest.prop.PropertyChecks
import org.scalacheck.Arbitrary

import cats.instances.all._

abstract class TraverseCheck[F[_]: Traverse](name: String)(implicit ArbFInt: Arbitrary[F[Int]]) extends CatsSuite with PropertyChecks {

test("Traverse[List].indexed") {
forAll { (fa: F[Int]) =>
fa.indexed.toList should === (fa.toList.zipWithIndex)
}
}

}

class TraverseListCheck extends TraverseCheck[List]("list")
class TraverseStreamCheck extends TraverseCheck[Stream]("stream")
class TraverseVectorCheck extends TraverseCheck[Vector]("vector")

class TraverseTestsAdditional extends CatsSuite {

def checkIndexedStackSafety[F[_]](fromRange: Range => F[Int])(implicit F: Traverse[F]): Unit = {
F.indexed(fromRange(1 to 500000))
()
}

test("Traverse[List].indexed stack safety") {
checkIndexedStackSafety[List](_.toList)
}

test("Traverse[Stream].indexed stack safety") {
checkIndexedStackSafety[Stream](_.toStream)
}

test("Traverse[Vector].indexed stack safety") {
checkIndexedStackSafety[Vector](_.toVector)
}
}

0 comments on commit eef6979

Please sign in to comment.