Heya, inspired by the <coroutines for Go-article>,...
# coroutines
j
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
This is weirdly similar to the previous question 😄
j
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
Ah, adding an extension function works.