From c081bdb3958bae4cd319b074699e683e9a6cd4d1 Mon Sep 17 00:00:00 2001 From: Cody Allen Date: Thu, 11 Feb 2016 08:31:15 -0500 Subject: [PATCH] Add .get method to StateT This gets the input state without modifying the state component. --- core/src/main/scala/cats/data/StateT.scala | 5 +++++ tests/src/test/scala/cats/tests/StateTTests.scala | 13 +++++++++++++ 2 files changed, 18 insertions(+) diff --git a/core/src/main/scala/cats/data/StateT.scala b/core/src/main/scala/cats/data/StateT.scala index b7e43af4bb..9e20c1cadb 100644 --- a/core/src/main/scala/cats/data/StateT.scala +++ b/core/src/main/scala/cats/data/StateT.scala @@ -108,6 +108,11 @@ final class StateT[F[_], S, A](val runF: F[S => F[(S, A)]]) extends Serializable def inspect[B](f: S => B)(implicit F: Monad[F]): StateT[F, S, B] = transform((s, _) => (s, f(s))) + /** + * Get the input state, without modifying the state. + */ + def get(implicit F: Monad[F]): StateT[F, S, S] = + inspect(identity) } object StateT extends StateTInstances { diff --git a/tests/src/test/scala/cats/tests/StateTTests.scala b/tests/src/test/scala/cats/tests/StateTTests.scala index 74d8f67f22..6673c628d8 100644 --- a/tests/src/test/scala/cats/tests/StateTTests.scala +++ b/tests/src/test/scala/cats/tests/StateTTests.scala @@ -77,6 +77,19 @@ class StateTTests extends CatsSuite { } } + test(".get and then .run produces same state as value"){ + forAll { (s: State[Long, Int], initial: Long) => + val (finalS, finalA) = s.get.run(initial).value + finalS should === (finalA) + } + } + + test(".get equivalent to flatMap with State.get"){ + forAll { (s: State[Long, Int]) => + s.get should === (s.flatMap(_ => State.get)) + } + } + test("StateT#transformS with identity is identity") { forAll { (s: StateT[List, Long, Int]) => s.transformS[Long](identity, (s, i) => i) should === (s)