Skip to content

Commit

Permalink
Adding StateT.modify
Browse files Browse the repository at this point in the history
  • Loading branch information
zainab-ali committed Jul 8, 2016
1 parent d7c1bb5 commit 90a2280
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
11 changes: 10 additions & 1 deletion core/src/main/scala/cats/data/StateT.scala
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,17 @@ object StateT extends StateTInstances {
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] =
def inspect[F[_], S, A](f: S => A)(implicit F: Applicative[F]): StateT[F, S, A] =
StateT(s => F.pure((s, f(s))))

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

def modify[F[_], S](f: S => S)(implicit F: Applicative[F]): StateT[F, S, Unit] =
StateT(s => F.pure((f(s), ())))

def modifyF[F[_], S](f: S => F[S])(implicit F: Applicative[F]): StateT[F, S, Unit] =
StateT(s => F.map(f(s))(s => (s, ())))
}

private[data] sealed trait StateTInstances extends StateTInstances1 {
Expand Down
26 changes: 25 additions & 1 deletion tests/src/test/scala/cats/tests/StateTTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,31 @@ 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))
val stateT: State[String, Int] = StateT.inspect(f)
state.run(s) should === (stateT.run(s))
}
}

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

test("State.modify and StateT.modify are consistent") {
forAll { (s: String, f: String => String) =>
val state: State[String, Unit] = State.modify(f)
val stateT: State[String, Unit] = StateT.modify(f)
state.run(s) should === (stateT.run(s))
}
}

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

0 comments on commit 90a2280

Please sign in to comment.