Skip to content

Instantly share code, notes, and snippets.

@clementgarbay
Created April 21, 2018 10:34
Show Gist options
  • Select an option

  • Save clementgarbay/49288c006252955c2a3c6139a61ca92a to your computer and use it in GitHub Desktop.

Select an option

Save clementgarbay/49288c006252955c2a3c6139a61ca92a to your computer and use it in GitHub Desktop.

Revisions

  1. clementgarbay created this gist Apr 21, 2018.
    20 changes: 20 additions & 0 deletions collections.kt
    Original 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()
    }
    }
    }