Skip to content

Commit 84f20ef

Browse files
authored
A method StateT.fromState turning State[A, F[B]] into StateT[F,A, B] is added. (#3524)
* A method `StateT.fromState` turning `State[A, F[B]]` into `StateT[F, A, B]` is added. * Usage of Applicative typeclass is desugared in the method `StateT.fromState` for the sake of consistency with the rest of the file.
1 parent d664b05 commit 84f20ef

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

core/src/main/scala/cats/data/IndexedStateT.scala

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,15 @@ private[data] trait CommonStateTConstructors {
199199

200200
def get[F[_], S](implicit F: Applicative[F]): IndexedStateT[F, S, S, S] =
201201
IndexedStateT(s => F.pure((s, s)))
202+
203+
/**
204+
* Turn `State[A, F[B]]` into `StateT[F, A, B]`
205+
*/
206+
def fromState[F[_], A, B](s: State[A, F[B]])(implicit F: Applicative[F]): StateT[F, A, B] =
207+
s.transformF { eval =>
208+
val (a, fb) = eval.value
209+
F.map(fb)((a, _))
210+
}
202211
}
203212

204213
object IndexedStateT extends IndexedStateTInstances with CommonStateTConstructors0 {

tests/src/test/scala/cats/tests/IndexedStateTSuite.scala

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,17 @@ class IndexedStateTSuite extends CatsSuite {
324324
}
325325
}
326326

327+
test("fromState correctly turns State[A, F[B]] into StateT[F, A, B]") {
328+
val state: State[Int, Option[Int]] = add1.map(Some.apply)
329+
import cats.implicits.catsStdInstancesForOption
330+
forAll { (initial: Int) =>
331+
StateT.fromState(state).run(initial).get should === {
332+
val (s, Some(result)) = state.run(initial).value
333+
(s, result)
334+
}
335+
}
336+
}
337+
327338
implicit val iso: Isomorphisms[IndexedStateT[ListWrapper, String, Int, *]] =
328339
Isomorphisms.invariant[IndexedStateT[ListWrapper, String, Int, *]](
329340
IndexedStateT.catsDataFunctorForIndexedStateT(ListWrapper.monad)

0 commit comments

Comments
 (0)