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

Marc Knaup

12/28/2019, 2:48 PM
Oh wow, proof of concept 😮 This one runs forever, recursively.
Copy code
suspend fun main() {
    recurse(1)
}


suspend fun recurse(n: Int) {
    if (n % 1000 == 0)
        delay(1)

    println(n)
    recurse(n+1)

    print("")
}
Question is now how to implement that manually, with
@RestrictsSuspension
and without the 1ms penalty 😄 And how to figure out a good
n % something
as it depends on the stack size usage of each function in the call stack.
r

Ruckus

12/28/2019, 4:52 PM
I can't answer all of your question, but you should at least be able to replace
delay(1)
with
yield()
1
m

Marc Knaup

12/29/2019, 1:11 AM
I've tried that, but it always overflows then 🤔
l

louiscad

12/30/2019, 3:08 PM
@Marc Knaup With which kotlinx.coroutines version and which dispatcher?
m

Marc Knaup

12/30/2019, 4:13 PM
1.3.3 and whatever dispatcher a
suspend fun main
is using.
l

louiscad

12/30/2019, 9:18 PM
It's using `Dispatchers.Default`… by default.
Can't you make the function tail recursive?
tailrec
m

Marc Knaup

12/31/2019, 7:40 AM
No, it’s a complex full-blown visitor pattern, and visitors can do whatever they like 🙂
That’s especially crazy with parallel recursive visitors 😄 start visiting -> visit node X using visitor 1 -> visitor1.visit(X) -> visit children -> visit node X using visitor 2 -> visitor2.visit(X) -> visit children -> visit node Y using visitor 1 -> visitor1.visit(Y) -> visit children -> visit node Y using visitor 2 -> visitor2.visit(Y) -> visit children -> and so on
visit children
and
visit node … using visitor …
are controlled by me.
visitor….visit(…)
can be arbitrary code, by every class that implements a Visitor.
l

louiscad

01/02/2020, 1:15 PM
I think @orangy or @elizarov did an experiment with such a recursive logic, they might be able to bring some valuable input from their experience.
m

Marc Knaup

01/02/2020, 1:27 PM
I’ve seen Roman’s work and it goes in the same direction 🙂
4 Views