https://kotlinlang.org logo
#coroutines
Title
# coroutines
j

Jarkko Miettinen

12/11/2023, 2:47 PM
Heya, inspired by the coroutines for Go-article, I thought that one good usage for coroutines would be turning push-iteration into pull-iteration (sequence + yield -> iterator). However, my naive approach runs into the problem that
SequenceScope
is restricted suspension scope and thus I cannot use the recursive approach defined there. In short, I'd like to turn this recursive approach into a iterator without manually writing the stack handling for such an iterator. Is there a way to do this?
s

Sam

12/11/2023, 2:48 PM
This is weirdly similar to the previous question 😄
j

Jarkko Miettinen

12/11/2023, 2:49 PM
Yeah, now that I read the thread there's clear overlap. I could write that with a Flow, but turning that into an Iterator (without copying all content over) seems hard to me.
It doesn't answer your question but it struck me as relevant
Actually I think the previous thread overcomplicated my thinking here. This is solvable just by updating your function signature:
Copy code
fun <T : Comparable<T>> inOrderTraversal(root: Node<T>?): Sequence<T> = sequence {
  suspend fun <T: Comparable<T>> SequenceScope<T>.walk(node: Node<T>?) {
    if (node == null) return

    when (node) {
      is InternalNode -> {
        walk(node.left)
        yield(node.value)
        walk(node.right)
      }
      is Leaf -> yield(node.value)
    }
  }
  walk(root)
}
thank you color 1
1
j

Jarkko Miettinen

12/11/2023, 2:58 PM
Ah, adding an extension function works.