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 14, 2017
1 parent fa81f97 commit 5742379
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 syntax.either._
* 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)(_.asLeft[A])
else pure(a.asRight[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(a.asRight[A])
else map(f)(_.asLeft[A])
}
iterateUntilM(i)(_ => f)(p)
}
}

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

0 comments on commit 5742379

Please sign in to comment.