bloodshura
06/27/2021, 4:12 PMList#sortedWith
that takes a comparator which can be suspended?
Suppose I'd need something like this:
someList.sortedWith { o1, o2 -> suspendedComparison(o1, o2) }
Where suspendedComparison
is a function which returns Int
(satisfying Comparator
) and is a suspend fun
...sortedWith
takes a Comparator
as an argument, whose SAM is not suspendable. But then, what are the alternatives? Will I need to implement a sorting algorithm from scratch just to make it suspendable?mbonnin
06/27/2021, 4:21 PMsuspendedComparison
in runBlocking {}
bloodshura
06/27/2021, 4:25 PMmbonnin
06/27/2021, 4:28 PMephemient
06/27/2021, 5:42 PMsuspend fun <T> List<T>.sortedWith(comparator: suspend (a: T, b: T) -> Int): List<T> {
if (size <= 1) return this
val first = first()
val (left, right) = drop(1).partition { comparator(first, it) >= 0 }
return left.sortedWith(comparator) + first + right.sortedWith(comparator)
}
suspend fun <T> List<T>.sortedWith(scope: CoroutineScope, comparator: suspend (a: T, b: T) -> Int): List<T> {
if (size <= 1) return this
val first = first()
val (left, right) = drop(1).partition { comparator(first, it) >= 0 }
val sortedLeft = scope.async { left.sortedWith(this, comparator) }
val sortedRight = scope.async { right.sortedWith(this, comparator) }
return sortedLeft.await() + first + sortedRight.await()
}
bloodshura
07/01/2021, 6:53 PM