Does Scala Iterator ++ (concat) use a recursively stack safe?

Suppose you are using an API that allows you to scroll through a set of results on pages. Each page returns an identifier for the next page.

This is the established idiom that you can use the Scala Iterator and your lazy concat (++) operator recursively for this:

def allResults: Iterator[Result] = {
  def nextPage(pageId: String): Iterator[Result] = {
    val page = invoke api
    Iterator(page.results) ++ nextPage(page.nextPageId)
  }
  val firstPage = invoke api
  Iterator(firstPage.results) ++ nextPage(firstPage.nextPageId)
}

Is this idiom stack safe? Or is there another efficiency to worry about?

+4
source share
2 answers

I believe that this is safe for the stack, in particular because the method ++accepts a call-by-call parameter, as you mentioned.

, "" , .

@tailrec, , , , fooobar.com/questions/70379/...

+2

StackOverflowError Scala 2.11.11 Iterator.++, Stream.#::. , ​​Iterator.++ Scala 2.11.11. Scala 2.12.2 :

def iter(n: Int): Iterator[Int] = if (n <= 0) Iterator.empty else { Iterator.single(n) ++ iter(n - 1) } iter(100000).foreach(print)

StackOverflowError Scala 2.11.11, Scala 2.12.2 . Stream.#:: . , Scala 2.11.11?

def stream(n: Int): Stream[Int] = if (n <= 0) Stream.empty else { n #:: stream(n - 1) } stream(1000000).foreach(print)

0

Source: https://habr.com/ru/post/1679997/


All Articles