Skip to content
Snippets Groups Projects
State.scala 719 B
Newer Older
package readerwriter.internal
/* You don't need to edit any of the files inside this package. These are the actual implementations, and you should
 * only use the provided methods, not rely on internal structure
 */

import applicative.Monad

case class State[S, A] private (run: S => (S, A))

case object State {
  implicit def stateMonad[S]: Monad[State[S, ?]] = new Monad[State[S, ?]] {
    override def unit[A](a: A): State[S, A] = State(s => (s, a))
    override def flatMap[A, B](fa: State[S, A])(f: A => State[S, B]): State[S, B] = State(s => {
      val (s1, a) = fa.run(s)
      f(a).run(s1)
    })
  }

  def get[S]: State[S, S] = State(s => (s, s))
  def set[S](s: S): State[S, Unit] = State(_ => (s, ()))
}