Created
December 20, 2024 22:31
-
-
Save jessestricker/c247928a474fffb5d3df3c877a92ecfb to your computer and use it in GitHub Desktop.
Comparator that compares lists lexicographically.
This file contains 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 characters
/** | |
* Returns a comparator that compares lists _lexicographically_ using the given [elementComparator]. | |
*/ | |
internal fun <T> lexicographicOrder(elementComparator: Comparator<T>): Comparator<List<T>> = | |
object : Comparator<List<T>> { | |
override fun compare(listA: List<T>, listB: List<T>): Int { | |
val iteratorA = listA.iterator() | |
val iteratorB = listB.iterator() | |
while (iteratorA.hasNext() && iteratorB.hasNext()) { | |
val elementA = iteratorA.next() | |
val elementB = iteratorB.next() | |
val ordering = elementComparator.compare(elementA, elementB) | |
if (ordering != 0) { | |
return ordering | |
} | |
} | |
return listA.size compareTo listB.size | |
} | |
} | |
/** Returns a comparator that compares lists _lexicographically_. */ | |
internal fun <T : Comparable<T>> lexicographicOrder(): Comparator<List<T>> = | |
lexicographicOrder(naturalOrder()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment