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 18, 2017
1 parent 3292b37 commit bcfd5e6
Showing 1 changed file with 6 additions and 16 deletions.
22 changes: 6 additions & 16 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 All @@ -107,9 +97,9 @@ import simulacrum.typeclass
def iterateWhileM[A](init: A)(f: A => F[A])(p: A => Boolean): F[A] =
tailRecM(init) { a =>
if (p(a))
map(f(a))(_.asLeft[A])
map(f(a))(Left(_))
else
pure(a.asRight[A])
pure(Right(a))
}

/**
Expand Down

0 comments on commit bcfd5e6

Please sign in to comment.