Skip to content

Instantly share code, notes, and snippets.

@globulon
Created February 15, 2012 20:52
Show Gist options
  • Select an option

  • Save globulon/1838926 to your computer and use it in GitHub Desktop.

Select an option

Save globulon/1838926 to your computer and use it in GitHub Desktop.
Mandatory definitions for State Monad
implicit def stateFunctor[S]() = new Functor[({type λ[α] = State[α,S]})#λ] {
def map[T, P >: T, U](source: State[T, S])(f: P => U): State[U, S] = new State[U, S]((s: S) => {
val (value, state) = source(s)
(f(value), state)
})
}
implicit def stateMonad[S]() = new Monad[({type λ[α] = State[α,S]})#λ]{
def apply[T](data: T) = new State((s: S) => (data, s))
def flatten[T](m: State[State[T, S], S]): State[T, S] = new State[T, S]((s: S) => {
val (mp, sp) = m(s)
mp(sp)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment