Skip to content

Instantly share code, notes, and snippets.

@ryohji
Last active November 28, 2019 12:04
Show Gist options
  • Save ryohji/854e5e428a028a405aa491746f957037 to your computer and use it in GitHub Desktop.
Save ryohji/854e5e428a028a405aa491746f957037 to your computer and use it in GitHub Desktop.
Direct product in Kotlin
fun <E> Collection<Collection<E>>.directProduct(): List<List<E>> =
if (isEmpty()) {
listOf()
} else {
val (head, rest) = first() to drop(1)
head.map(::listOf).let {
if (rest.isEmpty()) {
it
} else {
rest.directProduct().flatMap { tail -> it.map { h -> h + tail } }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment