Created
April 21, 2018 10:34
-
-
Save clementgarbay/49288c006252955c2a3c6139a61ca92a to your computer and use it in GitHub Desktop.
Safe transpose a list of unequal-length lists in Kotlin.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Safe transpose a list of unequal-length lists. | |
* | |
* Example: | |
* transpose(List(List(1, 2, 3), List(4, 5, 6), List(7, 8))) | |
* -> List(List(1, 4, 7), List(2, 5, 8), List(3, 6)) | |
*/ | |
fun <E> transpose(xs: List<List<E>>): List<List<E>> { | |
// Helpers | |
fun <E> List<E>.head(): E = this.first() | |
fun <E> List<E>.tail(): List<E> = this.takeLast(this.size - 1) | |
fun <E> E.append(xs: List<E>): List<E> = listOf(this).plus(xs) | |
xs.filter { it.isNotEmpty() }.let { ys -> | |
return when (ys.isNotEmpty()) { | |
true -> ys.map { it.head() }.append(transpose(ys.map { it.tail() })) | |
else -> emptyList() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi there, I noticed that this will 'collapse' values if they're missing, for example if the input's 2nd row, 3rd column is missing, the transpose will have an element for the 3rd row, 2nd column.
I wrote an alternative that will replace missing elements with
null
.And because I felt like pre-optimising, I used Sequences to defer computation.
usage
result