Skip to content

Commit

Permalink
Add stateTraverse and 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 e3aa1ff
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
23 changes: 23 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 @@ -32,6 +34,17 @@ import simulacrum.typeclass
*/
def traverse[G[_]: Applicative, A, B](fa: F[A])(f: A => G[B]): G[F[B]]

/**
* Traverse with a function returning state.
*
* Given a function which returns state, thread the state through
* the running of this function on all the values in F, returning
* F[B] in the state context.
*/
def stateTraverse[S, A, B](fa: F[A])(f: A => State[S, B]): State[S, F[B]] =
State[S, F[B]](s =>
traverse[State[S, ?] , A, B](fa)(f).run(s).value)

/**
* A traverse followed by flattening the inner result.
*
Expand Down Expand Up @@ -97,4 +110,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)] =
stateTraverse(fa)(a => State((s: Int) => (s + 1, (a, s)))).runA(0).value
}
6 changes: 6 additions & 0 deletions tests/src/test/scala/cats/tests/ListTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,10 @@ class ListTests extends CatsSuite {
l.show should === (l.toString)
}
}

test("indexed consistent with zipWithIndex") {
forAll { (fa: List[String]) =>
Traverse[List].indexed(fa) should === (fa.zipWithIndex)
}
}
}

0 comments on commit e3aa1ff

Please sign in to comment.