Skip to content

Commit

Permalink
A method StateT.fromState turning State[A, F[B]] into `StateT[F,A…
Browse files Browse the repository at this point in the history
…, 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.
  • Loading branch information
akopich authored Jul 21, 2020
1 parent d664b05 commit 84f20ef
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
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

0 comments on commit 84f20ef

Please sign in to comment.