Dominaezzz
12/02/2019, 3:53 PMsealed class Tree {
data class Parent(val children: List<Tree>): Tree()
data class Leaf(val value: Int): Tree()
}
fun Tree.simpleSum(): Int {
return when (this) {
is Tree.Parent -> children.map { it.simpleSum() }.sum()
is Tree.Leaf -> value
}
}
fun Tree.concurrentSum(): Int {
return when (this) {
is Tree.Parent -> runBlocking {
children.map { async { it.simpleSum() } }
.awaitAll().sum()
}
is Tree.Leaf -> value
}
}
suspend fun Tree.questionableSum(): Int {
return when (this) {
is Tree.Parent -> coroutineScope {
children.map { async { it.questionableSum() } }
.awaitAll().sum()
}
is Tree.Leaf -> value
}
}
I basically want to sum up all the nodes in the tree. Right now I create a Job
for every immediate child of the root (concurrentSum
), but I might not be using all the parallelism available. I'm tempted to recursively create a Job
at every node (questionableSum
) which would use all the parallelism but I get the feeling that that's not the way to go.
Is there a "right" way to go about this?bdawg.io
12/02/2019, 10:26 PMquestionableSum
implementation. What is the feeling that you're getting?
There are certainly alternatives, but not sure that it would necessarily be "better" or more "right"Dominaezzz
12/03/2019, 11:42 AMbdawg.io
12/03/2019, 5:02 PM