Skip to content

Instantly share code, notes, and snippets.

@folone
Created October 18, 2012 12:21
Show Gist options
  • Save folone/3911448 to your computer and use it in GitHub Desktop.
Save folone/3911448 to your computer and use it in GitHub Desktop.
State exercise
case class State[S, +A](run: S ⇒ (A, S)) {
def map[B](f: A => B): State[S, B] =
State(s ⇒ {
val (a, t) = run(s)
(f(a), t)
})
def flatMap[B](f: A ⇒ State[S, B]): State[S, B] =
State(s ⇒ {
val (a, t) = run(s)
f(a) run t
})
def modify(f: S ⇒ S): State[S, A] =
State(s ⇒ {
val (a, t) = run(s)
(a, f(s))
})
def put[S, A](s: S): State[S, Unit] = State(_ ⇒ ((), s))
object State {
def point[S, A](a: => A): State[S, A] =
State(s ⇒ (a, s))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment