Skip to content

Commit

Permalink
Implement iterateWhile in terms of iterateWhileM
Browse files Browse the repository at this point in the history
  • Loading branch information
drbild committed Aug 30, 2017
1 parent 3f7dd4d commit 60d8e5a
Showing 1 changed file with 4 additions and 14 deletions.
18 changes: 4 additions & 14 deletions core/src/main/scala/cats/Monad.scala
Original file line number Diff line number Diff line change
Expand Up @@ -76,29 +76,19 @@ import simulacrum.typeclass
* Execute an action repeatedly until its result fails to satisfy the given predicate
* and return that result, discarding all others.
*/
def iterateWhile[A](f: F[A])(p: A => Boolean): F[A] = {
def iterateWhile[A](f: F[A])(p: A => Boolean): F[A] =
flatMap(f) { i =>
tailRecM(i) { a =>
if (p(a))
map(f)(Left(_))
else pure(Right(a))
}
iterateWhileM(i)(_ => f)(p)
}
}

/**
* Execute an action repeatedly until its result satisfies the given predicate
* and return that result, discarding all others.
*/
def iterateUntil[A](f: F[A])(p: A => Boolean): F[A] = {
def iterateUntil[A](f: F[A])(p: A => Boolean): F[A] =
flatMap(f) { i =>
tailRecM(i) { a =>
if (p(a))
pure(Right(a))
else map(f)(Left(_))
}
iterateUntilM(i)(_ => f)(p)
}
}

/**
* Apply a monadic function iteratively until its result fails
Expand Down

0 comments on commit 60d8e5a

Please sign in to comment.