Skip to content
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
9 changes: 9 additions & 0 deletions core/src/main/scala/cats/data/IndexedStateT.scala
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,15 @@ private[data] trait CommonStateTConstructors {

def get[F[_], S](implicit F: Applicative[F]): IndexedStateT[F, S, S, S] =
IndexedStateT(s => F.pure((s, s)))

/**
* Turn `State[A, F[B]]` into `StateT[F, A, B]`
*/
def fromState[F[_], A, B](s: State[A, F[B]])(implicit F: Applicative[F]): StateT[F, A, B] =
s.transformF { eval =>
val (a, fb) = eval.value
F.map(fb)((a, _))
}
}

object IndexedStateT extends IndexedStateTInstances with CommonStateTConstructors0 {
Expand Down
11 changes: 11 additions & 0 deletions tests/src/test/scala/cats/tests/IndexedStateTSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,17 @@ class IndexedStateTSuite extends CatsSuite {
}
}

test("fromState correctly turns State[A, F[B]] into StateT[F, A, B]") {
val state: State[Int, Option[Int]] = add1.map(Some.apply)
import cats.implicits.catsStdInstancesForOption
forAll { (initial: Int) =>
StateT.fromState(state).run(initial).get should === {
val (s, Some(result)) = state.run(initial).value
(s, result)
}
}
}

implicit val iso: Isomorphisms[IndexedStateT[ListWrapper, String, Int, *]] =
Isomorphisms.invariant[IndexedStateT[ListWrapper, String, Int, *]](
IndexedStateT.catsDataFunctorForIndexedStateT(ListWrapper.monad)
Expand Down