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

Implement LazyList tailRecM using Iterator.unfold #2964

Merged
merged 1 commit into from
Aug 2, 2019
Merged
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
54 changes: 6 additions & 48 deletions core/src/main/scala-2.13+/cats/instances/lazyList.scala
Original file line number Diff line number Diff line change
Expand Up @@ -69,56 +69,14 @@ trait LazyListInstances extends cats.kernel.instances.StreamInstances {
fa.zipWithIndex

def tailRecM[A, B](a: A)(fn: A => LazyList[Either[A, B]]): LazyList[B] = {
val it: Iterator[B] = new Iterator[B] {
var stack: List[Iterator[Either[A, B]]] = Nil
var state: Either[A, Option[B]] = Left(a)

@tailrec
def advance(): Unit = stack match {
case head :: tail =>
if (head.hasNext) {
head.next match {
case Right(b) =>
state = Right(Some(b))
case Left(a) =>
val nextFront = fn(a).iterator
stack = nextFront :: stack
advance()
}
} else {
stack = tail
advance()
}
case Nil =>
state = Right(None)
}

@tailrec
def hasNext: Boolean = state match {
case Left(a) =>
// this is the first run
stack = fn(a).iterator :: Nil
advance()
hasNext
case Right(o) =>
o.isDefined
}

@tailrec
def next(): B = state match {
case Left(a) =>
// this is the first run
stack = fn(a).iterator :: Nil
advance()
next()
case Right(o) =>
val b = o.get
advance()
b
val kernel = Iterator.unfold[Option[B], Iterator[Either[A, B]]](Iterator(Left(a))) { it =>
Copy link
Contributor

Choose a reason for hiding this comment

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

two small notes, I bet this would be faster if we did:

unfold[Option[B], List[Iterator[Either[A, B]]])(Iterator.single(Left(a)) :: Nil) {
  case Nil => None
  case nonempty@(h :: t) =>
    if (!h.hasNext) Some((None, t))
    else h.next match {
      case Left(a) => Some((None, fn(a) :: nonempty))
      case Right(b) => Some((Some(b), nonempty))
    } 
}

if (!it.hasNext) None
else it.next match {
case Left(a) => Some((None, fn(a).iterator ++ it))
case Right(b) => Some((Some(b), it))
}
}

LazyList.from(it)
LazyList.from(kernel.collect { case Some(v) => v })
}

override def exists[A](fa: LazyList[A])(p: A => Boolean): Boolean =
Expand Down