Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created October 9, 2019 12:13
Show Gist options
  • Save fancellu/082ee9614046081aa06a250960eab9ff to your computer and use it in GitHub Desktop.
Save fancellu/082ee9614046081aa06a250960eab9ff to your computer and use it in GitHub Desktop.
Example of how to use the Cats State datatype to encapsulate state changes in an immutable manner
(List(pushed1, pushed1, y, z),pushed1)
Stack is currently List(a, b, c)
(List(pushed2, saw a, a, b, c),pure)
Stack is currently List(b, c)
(List(pushed2_no_a, b, c),pure)
import cats._
import cats.data._
import cats.implicits._
// Example of how to use the Cats State datatype to encapsulate state changes in an immutable manner
// Helps us remove error prone boilerplate when chaining state transitions
object StateExample extends App {
type Stack = List[String]
// operations, they all take Stack
val pop = State[Stack, String] {
case head :: tail => (tail, head)
case Nil => sys.error("stack is empty")
}
def push(a: String) = State[Stack, Unit](stack => (a :: stack, ()))
// note how we compose a new operation with the for comprehension
// State methods refer to the previous state
def stackEdit1(pushed: String): State[Stack, String] = for {
_ <- pop
_ <- push(pushed)
_ <- push(pushed)
_ <- push(pushed)
out <- pop
} yield out
def stackEdit2(pushed: String): State[Stack, String] = for {
stack <- State.get[Stack] // we access the current Stack
_ = println(s"Stack is currently $stack")
_ <- if (stack.headOption == "a".some) push("saw a") else State.get[Stack]
_ <- push(pushed)
_ <- push(pushed)
_ <- pop
out <- State.pure("pure")
// _ <- State.set[Stack](stack) // this would set stack back to how it was in the beginning
} yield out
println(stackEdit1("pushed1").run(List("x", "y", "z")).value)
println(stackEdit2("pushed2").run(List("a", "b", "c")).value)
println(stackEdit2("pushed2_no_a").run(List("b", "c")).value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment