Created
April 21, 2018 10:34
-
-
Save clementgarbay/49288c006252955c2a3c6139a61ca92a to your computer and use it in GitHub Desktop.
Revisions
-
clementgarbay created this gist
Apr 21, 2018 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,20 @@ /** * 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() } } }