Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add state method to MonadState #1651

Merged
merged 5 commits into from
May 10, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions core/src/main/scala/cats/ApplicativeError.scala
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,24 @@ trait ApplicativeError[F[_], E] extends Applicative[F] {
case Success(a) => pure(a)
case Failure(e) => raiseError(e)
}

/**
* Convert from scala.Either
*
* Example:
* {{{
* scala> import cats.ApplicativeError
* scala> import cats.instances.option._
*
* scala> ApplicativeError[Option, Unit].fromEither(Right(1))
* res0: scala.Option[Int] = Some(1)
*
* scala> ApplicativeError[Option, Unit].fromEither(Left(()))
* res1: scala.Option[Nothing] = None
* }}}
*/
def fromEither[A](x: E Either A): F[A] =
x.fold(raiseError, pure)
}

object ApplicativeError {
Expand Down
21 changes: 21 additions & 0 deletions core/src/main/scala/cats/MonadState.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,27 @@ package cats
* }}}
*/
trait MonadState[F[_], S] extends Monad[F] {

/**
* Embed a state action into the monad.
*
* Example:
* {{{
* scala> import cats.MonadState
* scala> import cats.data.StateT
* scala> import cats.instances.list._
*
* scala> val M = MonadState[StateT[List, Int, ?], Int]
* scala> import M._
*
* scala> val st: StateT[List, Int, Int] = state(s => (s + 1, s * 100))
* scala> st.run(1)
* res0: List[(Int, Int)] = List((2,100))
* }}}
*/
def state[A](f: S => (S, A)): F[A] =
flatMap(get)(s => f(s) match { case (s, a) => map(set(s))(_ => a) })

def get: F[S]

def set(s: S): F[Unit]
Expand Down