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 more doctest to Monad and FlatMap #4427

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 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
26 changes: 26 additions & 0 deletions core/src/main/scala/cats/FlatMap.scala
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,22 @@ trait FlatMap[F[_]] extends Apply[F] with FlatMapArityFunctions[F] {

/**
* `if` lifted into monad.
*
* Example:
* {{{
* scala> import cats.Eval
* scala> import cats.syntax.all._
*
* scala> val b1 = Eval.now(true)
* scala> val asString1 = b1.ifM(Eval.now("it's true!"), Eval.now("it's false!"))
* scala> asString1.value
* res0: String = it's true!

* scala> val b2 = Eval.now(false)
* scala> val asString2 = b2.ifM(Eval.now("it's true!"), Eval.now("it's false!"))
* scala> asString2.value
* res1: String = it's false!
* }}}
*/

def ifM[B](fa: F[Boolean])(ifTrue: => F[B], ifFalse: => F[B]): F[B] =
Expand Down Expand Up @@ -207,6 +223,16 @@ trait FlatMap[F[_]] extends Apply[F] with FlatMapArityFunctions[F] {
* This repeats an F until we get defined values. This can be useful
* for polling type operations on State (or RNG) Monads, or in effect
* monads.
*
* Example:
* {{{
* scala> import cats.data.State
* scala> import cats.syntax.all._
* scala> val counter = State { i: Int => (i+1, if(i>100) Some(i) else None)}
* scala> val eval = counter.untilDefinedM.run(0)
* scala> eval.value
* res0: (Int, Int) = (102,101)
* }}}
*/

def untilDefinedM[A](foa: F[Option[A]]): F[A] = {
Expand Down
90 changes: 90 additions & 0 deletions core/src/main/scala/cats/Monad.scala
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,18 @@ trait Monad[F[_]] extends FlatMap[F] with Applicative[F] {
* Collects the results into an arbitrary `Alternative` value, such as a `Vector`.
* This implementation uses append on each evaluation result,
* so avoid data structures with non-constant append performance, e.g. `List`.
*
* Example:
* {{{
* scala> import cats.{Id, Monad}
* scala> import cats.data.StateT
* scala> import cats.syntax.all._
* scala> val appendStr: StateT[Id, String, Unit] = StateT.modify(_ + "a")
* scala> val appendStrAndGet: StateT[Id, String, String] = appendStr *> StateT.get
* scala> val (result, agg) = appendStrAndGet.whileM[Vector](StateT.inspect(i => !(i.length >= 5))).run("")
* result: String = aaaaa
* agg: Vector[String] = Vector(a, aa, aaa, aaaa, aaaaa)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of StateT[Id, ...] can't we just use State? The issue with StateT[Id, ...] is that actually it is not stacksafe.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, should I use State also in all other examples that uses StateT or just this one?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. You should never use StateT[Id.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. I'm using State now, but there's some results that's previous result + 1, like in iterateUntilM. Is that okay?

* }}}
*/

def whileM[G[_], A](p: F[Boolean])(body: => F[A])(implicit G: Alternative[G]): F[G[A]] = {
Expand All @@ -60,6 +72,16 @@ trait Monad[F[_]] extends FlatMap[F] with Applicative[F] {
* Execute an action repeatedly as long as the given `Boolean` expression
* returns `true`. The condition is evaluated before the loop body.
* Discards results.
*
* Example:
* {{{
* scala> import cats.{Id, Monad}
* scala> import cats.data.StateT
* scala> import cats.syntax.all._
* scala> val appendStr: StateT[Id, String, Unit] = StateT.modify(_ + "a")
* scala> val (result, _) = appendStr.whileM_(StateT.inspect(i => !(i.length >= 3))).run("")
* result: String = aaa
* }}}
*/

def whileM_[A](p: F[Boolean])(body: => F[A]): F[Unit] = {
Expand All @@ -80,6 +102,18 @@ trait Monad[F[_]] extends FlatMap[F] with Applicative[F] {
* arbitrary `Alternative` value, such as a `Vector`.
* This implementation uses append on each evaluation result,
* so avoid data structures with non-constant append performance, e.g. `List`.
*
* Example:
* {{{
* scala> import cats.{Id, Monad}
* scala> import cats.data.StateT
* scala> import cats.syntax.all._
* scala> val increment: StateT[Id, Int, Unit] = StateT.modify(_ + 1)
* scala> val incrementAndGet: StateT[Id, Int, Int] = increment *> StateT.get
* scala> val (result, aggregation) = incrementAndGet.untilM[Vector](StateT.inspect(_ >= 5)).run(-1)
* result: Int = 5
* aggregation: Vector[Int] = Vector(0, 1, 2, 3, 4, 5)
* }}}
*/
def untilM[G[_], A](f: F[A])(cond: => F[Boolean])(implicit G: Alternative[G]): F[G[A]] = {
val p = Eval.later(cond)
Expand All @@ -89,6 +123,16 @@ trait Monad[F[_]] extends FlatMap[F] with Applicative[F] {
/**
* Execute an action repeatedly until the `Boolean` condition returns `true`.
* The condition is evaluated after the loop body. Discards results.
*
* Example:
* {{{
* scala> import cats.{Id, Monad}
* scala> import cats.data.StateT
* scala> import cats.syntax.all._
* scala> val increment: StateT[Id, Int, Unit] = StateT.modify(_ + 1)
* scala> val (result, _) = increment.untilM_(StateT.inspect(_ >= 5)).run(-1)
* result: Int = 5
* }}}
*/
def untilM_[A](f: F[A])(cond: => F[Boolean]): F[Unit] = {
val p = Eval.later(cond)
Expand All @@ -98,6 +142,17 @@ trait Monad[F[_]] extends FlatMap[F] with Applicative[F] {
/**
* Execute an action repeatedly until its result fails to satisfy the given predicate
* and return that result, discarding all others.
*
* Example:
* {{{
* scala> import cats.{Id, Monad}
* scala> import cats.data.StateT
* scala> import cats.syntax.all._
* scala> val increment: StateT[Id, Int, Unit] = StateT.modify(_ + 1)
* scala> val incrementAndGet: StateT[Id, Int, Int] = increment *> StateT.get
* scala> val (result, _) = incrementAndGet.iterateWhile(_ < 5).run(-1)
* result: Int = 5
* }}}
*/
def iterateWhile[A](f: F[A])(p: A => Boolean): F[A] =
flatMap(f) { i =>
Expand All @@ -107,6 +162,17 @@ trait Monad[F[_]] extends FlatMap[F] with Applicative[F] {
/**
* Execute an action repeatedly until its result satisfies the given predicate
* and return that result, discarding all others.
*
* Example:
* {{{
* scala> import cats.{Id, Monad}
* scala> import cats.data.StateT
* scala> import cats.syntax.all._
* scala> val increment: StateT[Id, Int, Unit] = StateT.modify(_ + 1)
* scala> val incrementAndGet: StateT[Id, Int, Int] = increment *> StateT.get
* scala> val (result, _) = incrementAndGet.iterateUntil(_ == 5).run(-1)
* result: Int = 5
* }}}
*/
def iterateUntil[A](f: F[A])(p: A => Boolean): F[A] =
flatMap(f) { i =>
Expand All @@ -116,6 +182,18 @@ trait Monad[F[_]] extends FlatMap[F] with Applicative[F] {
/**
* Apply a monadic function iteratively until its result fails
* to satisfy the given predicate and return that result.
*
* Example:
* {{{
* scala> import cats.{Id, Monad}
* scala> import cats.data.StateT
* scala> import cats.syntax.all._
* scala> val increment: StateT[Id, Int, Unit] = StateT.modify(_ + 1)
* scala> val incrementAndGet: StateT[Id, Int, Int] = increment *> StateT.get
* scala> val (n, sum) = 0.iterateWhileM(s => incrementAndGet.map(_ + s))(_ < 5).run(0)
* n: Int = 3
* sum: Int = 6
* }}}
*/
def iterateWhileM[A](init: A)(f: A => F[A])(p: A => Boolean): F[A] =
tailRecM(init) { a =>
Expand All @@ -128,6 +206,18 @@ trait Monad[F[_]] extends FlatMap[F] with Applicative[F] {
/**
* Apply a monadic function iteratively until its result satisfies
* the given predicate and return that result.
*
* Example:
* {{{
* scala> import cats.{Id, Monad}
* scala> import cats.data.StateT
* scala> import cats.syntax.all._
* scala> val increment: StateT[Id, Int, Unit] = StateT.modify(_ + 1)
* scala> val incrementAndGet: StateT[Id, Int, Int] = increment *> StateT.get
* scala> val (n, sum) = 0.iterateUntilM(s => incrementAndGet.map(_ + s))(_ > 5).run(0)
* n: Int = 3
* sum: Int = 6
* }}}
*/
def iterateUntilM[A](init: A)(f: A => F[A])(p: A => Boolean): F[A] =
iterateWhileM(init)(f)(!p(_))
Expand Down