Decorate-sort-undecorate idiom: Difference between revisions

Content added Content deleted
Line 596: Line 596:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
Kotlin already has a `sortedBy` function that can sort using a key extractor directly, so there is no need to decorate/undecorate. Nevertheless, the code example below shows how to decorate, sort and undecorate.

<syntaxhighlight lang="kotlin">
<syntaxhighlight lang="kotlin">
fun main() {
fun main() {
val list = listOf("Rosetta", "Code", "is", "a", "programming", "chrestomathy", "site")
val list = listOf("Rosetta", "Code", "is", "a", "programming", "chrestomathy", "site")
println(sorted(list, String::length))
println(list.sortedBySchwartzian(String::length))
}
}


/**
fun <T, C: Comparable<C>> sorted(list: Collection<T>, keyFn: (T) -> C): List<T> =
* Returns a sorted list using the Schwartzian Transform which guarantees minimal use of the
list
* key extractor function. Use when the key extractor function is an expensive operation.
.map { it to keyFn(it) }
*/
fun <T, R: Comparable<R>> Collection<T>.sortedBySchwartzian(keyFn: (T) -> R): List<T> =
this.map { it to keyFn(it) }
.sortedBy { it.second }
.sortedBy { it.second }
.map { it.first }
.map { it.first }