Skip to content

Commit

Permalink
Add mapWithIndex to Traverse; implement indexed in terms of mapWithIndex
Browse files Browse the repository at this point in the history
  • Loading branch information
andyscott committed Jul 7, 2017
1 parent 4413058 commit 8c6e3e6
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
5 changes: 4 additions & 1 deletion core/src/main/scala/cats/Traverse.scala
Original file line number Diff line number Diff line change
Expand Up @@ -108,5 +108,8 @@ import simulacrum.typeclass
* `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
mapWithIndex(fa)((a, i) => (a, i))

def mapWithIndex[A, B](fa: F[A])(f: (A, Int) => B): F[B] =
traverse(fa)(a => State((s: Int) => (s + 1, f(a, s)))).runA(0).value
}
6 changes: 6 additions & 0 deletions tests/src/test/scala/cats/tests/TraverseTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ abstract class TraverseCheck[F[_]: Traverse](name: String)(implicit ArbFInt: Arb
}
}

test(s"Traverse[$name].mapWithIndex") {
forAll { (fa: F[Int]) =>
fa.mapWithIndex((a, i) => (a, i)).toList should === (fa.toList.zipWithIndex)
}
}

}

class TraverseListCheck extends TraverseCheck[List]("list")
Expand Down

0 comments on commit 8c6e3e6

Please sign in to comment.