Skip to content

Add cross join (#1) #5203

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions libraries/stdlib/samples/test/samples/collections/collections.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1033,4 +1033,30 @@ class Collections {
}

}

class BinaryOperations {
@Sample
fun crossJoinToPairs() {
val colors = listOf("green", "yellow")
val fruits = listOf("apple", "banana")
val pairs = colors crossJoin fruits
assertPrints(pairs.toList(), "[(green, apple), (green, banana), (yellow, apple), (yellow, banana)]")
}

@Sample
fun crossJoinWithTransformation() {
data class Fruit(val color: String, val type: String)
val colors = listOf("green", "yellow")
val fruits = listOf("apple", "banana")

val transformedPairs = crossJoin(colors, fruits) { color, type ->
Fruit(color, type)
}
assertPrints(
transformedPairs.toList(),
"[Fruit(color=green, type=apple), Fruit(color=green, type=banana), Fruit(color=yellow, type=apple), Fruit(color=yellow, type=banana)]"
)
}

}
}
40 changes: 40 additions & 0 deletions libraries/stdlib/src/kotlin/collections/Collections.kt
Original file line number Diff line number Diff line change
Expand Up @@ -519,3 +519,43 @@ internal fun <T> collectionToArrayCommonImpl(collection: Collection<*>, array: A
* Returns the given [array].
*/
internal expect fun <T> terminateCollectionToArray(collectionSize: Int, array: Array<T>): Array<T>

/**
* Returns a list containing all possible pairs with left field from the first collection,
* and the right field from the second collection.
*
* The returned set preserves the element iteration order of both original collections.
* It begins with all the pairs with the first element of left collection,
* combined with all the elements of the right one in the order of the right collection.
*
* @sample samples.collections.Collections.BinaryOperations.crossJoinToPairs
*/
public infix fun <T, U> Collection<T>.crossJoin(other: Collection<U>) =
crossJoin(this, other) { left: T, right: U ->
Pair(left, right)
}

/**
* Returns a list containing all possible pairs with left field from the first collection,
* and the right field from the second collection,
* applying the provided transformation against those pairs.
*
* The returned set preserves the element iteration order of both original collections.
* It begins with all the pairs with the first element of left collection,
* combined with all the elements of the right one in the order of the right collection.
*
* @sample samples.collections.Collections.BinaryOperations.crossJoinWithTransformation
*/
fun <T, U, V> crossJoin(
left: Collection<T>,
right: Collection<U>,
transformation: (left: T, right: U) -> V,
): Sequence<V> {
return sequence {
left.forEach { leftElement ->
right.forEach { rightElement ->
yield(transformation(leftElement, rightElement))
}
}
}
}
Comment on lines +538 to +561
Copy link

@rlaope rlaope Jan 7, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on the crossJoin implementation you've provided, I believe it's possible to extend the concept to combine multiple elements from multiple collections, not just pairs of two elements. This could be achieved by creating a function that takes a list of collections and performs a multi-element cross join operation, producing combinations of elements from each collection.

The function signature could look something like this:

fun <T, V> multiCrossJoin(
    collections: List<Collection<T>>,
    transformation: (List<T>) -> V
): Sequence<V> {
    var result: Sequence<List<T>> = sequenceOf(emptyList())

    for (collection in collections) {
        result = result.flatMap { acc ->
            collection.map { element -> acc + element }
        }
    }

    return result.map { transformation(it) }
}

This function would take a list of collections and a transformation function, and it would perform a multi-element cross join operation to generate combinations of elements from each collection. The implementation would involve iterating through each collection and combining the elements to produce the desired combinations.

I believe that such a function would provide a flexible and powerful way to generate combinations from multiple collections of elements.

Copy link
Contributor Author

@AlexCue987 AlexCue987 Jan 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on the crossJoin implementation you've provided, I believe it's possible to extend the concept to combine multiple elements from multiple collections, not just pairs of two elements. This could be achieved by creating a function that takes a list of collections and performs a multi-element cross join operation, producing combinations of elements from each collection.

The function signature could look something like this:

fun <T, V> multiCrossJoin(
    collections: List<Collection<T>>,
    transformation: (List<T>) -> V
): Sequence<V> {
    var result: Sequence<List<T>> = sequenceOf(emptyList())

    for (collection in collections) {
        result = result.flatMap { acc ->
            collection.map { element -> acc + element }
        }
    }

    return result.map { transformation(it) }
}

This function would take a list of collections and a transformation function, and it would perform a multi-element cross join operation to generate combinations of elements from each collection. The implementation would involve iterating through each collection and combining the elements to produce the desired combinations.

I believe that such a function would provide a flexible and powerful way to generate combinations from multiple collections of elements.

You are solving a different problem: all elements in your collections have the same type T. The whole point of this PR is to handle pairs of elements with different types, left: T, right: U.

Cross Join

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are solving a different problem: all elements in your collections have the same type T. The whole point of this PR is to handle pairs of elements with different types, left: T, right: U.

Cross Join

Sure, I understand. It seems that I overlooked the fact that the types of "left" and "right" are different. I created a function to find all possible combinations of elements of the same type, and it looks like you implemented something different. If this PR gets merged, I will try implementing it based on this idea and submit another PR. Thank you.

51 changes: 51 additions & 0 deletions libraries/stdlib/test/collections/CrossJoinTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package test.collections

import kotlin.test.*

class CrossJoinTest {
private val colors = listOf("green", "yellow")
private val fruits = listOf("apple", "banana")

@Test fun emptyLeftCollection() {
val empty = listOf<String>() crossJoin fruits
assertFalse { empty.iterator().hasNext() }
}

@Test fun emptyRightCollection() {
val empty = colors crossJoin listOf<String>()
assertFalse { empty.iterator().hasNext() }
}

@Test fun emptyBothCollections() {
val empty = listOf<String>() crossJoin listOf<String>()
assertFalse { empty.iterator().hasNext() }
}

@Test fun crossJoinToPairs() {
val notEmpty = colors crossJoin fruits
assertEquals(listOf(
Pair("green", "apple"),
Pair("green", "banana"),
Pair("yellow", "apple"),
Pair("yellow", "banana"),
), notEmpty.toList())
}

@Test fun crossJoinWithTranformation() {
data class Fruit(val color: String, val type: String)

val notEmpty = crossJoin(colors, fruits) { color, type ->
Fruit(color, type)
}

assertEquals(
listOf(
Fruit("green", "apple"),
Fruit("green", "banana"),
Fruit("yellow", "apple"),
Fruit("yellow", "banana")
), notEmpty.toList()
)
}
}