Skip to content

Instantly share code, notes, and snippets.

@ryohji
Created November 28, 2019 12:17
Show Gist options
  • Save ryohji/dfe18eafcdc1dddd8792556a0352e254 to your computer and use it in GitHub Desktop.
Save ryohji/dfe18eafcdc1dddd8792556a0352e254 to your computer and use it in GitHub Desktop.
fun <E, F, ES : Collection<E>, FS : Collection<F>> directProduct(es: ES, fs: FS): Set<Pair<E, F>> =
fs.flatMap { f -> es.map { e -> e to f } }.toSet()
fun <A> flatten(pair: Pair<*, A>): List<A> {
val xs = mutableListOf(pair.second)
var x: Any? = pair.first
while (x is Pair<*, *>) {
xs.add(0, x.second as A)
x = x.first
}
xs.add(0, x as A)
return xs
}
// directProduct(setOf(1, 2, 3), setOf('a', 'b'))
// or
// listOf(setOf(1, 2, 3), setOf('a', 'b')).reduce(::directProduct)
// listOf(setOf(1, 2, 3), setOf('a', 'b'), setOf('X', 'Y', 'Z')).reduce(::directProduct)
// .map { flatten(it as Pair<*, *>) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment