Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding lift and inspect to StateT #1169

Merged
merged 3 commits into from
Jul 13, 2016
Merged
Show file tree
Hide file tree
Changes from 2 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
6 changes: 6 additions & 0 deletions core/src/main/scala/cats/data/StateT.scala
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,12 @@ object StateT extends StateTInstances {

def pure[F[_], S, A](a: A)(implicit F: Applicative[F]): StateT[F, S, A] =
StateT(s => F.pure((s, a)))

def lift[F[_], S, A](fa: F[A])(implicit F: Applicative[F]): StateT[F, S, A] =
StateT(s => F.map(fa)(a => (s, a)))

def inspect[F[_], S, A](f: S => F[A])(implicit F: Applicative[F]): StateT[F, S, A] =
StateT(s => F.map(f(s))(a => (s, a)))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we have inspect take S => A and create a separate inspectF for S => F[A]? It seems like the simple S => A case might be pretty common, so it might be nice to make it concise.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. I'm thinking of adding a modify taking S => S and a modifyF taking S => F[S] while
I'm at it.

}

private[data] sealed trait StateTInstances extends StateTInstances1 {
Expand Down
16 changes: 16 additions & 0 deletions tests/src/test/scala/cats/tests/StateTTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,22 @@ class StateTTests extends CatsSuite {
}
}

test("State.inspect and StateT.inspect are consistent") {
forAll { (s: String, f: String => Int) =>
val state: State[String, Int] = State.inspect(f)
val stateT: State[String, Int] = StateT.inspect(f.andThen(Eval.now))
state.run(s) should === (stateT.run(s))
}
}

test("State.pure and StateT.lift are consistent") {
forAll { (s: String, i: Int) =>
val state: State[String, Int] = State.pure(i)
val stateT: State[String, Int] = StateT.lift(Eval.now(i))
state.run(s) should === (stateT.run(s))
}
}

test("Cartesian syntax is usable on State") {
val x = add1 *> add1
x.runS(0).value should === (2)
Expand Down