run.smt.ktest.util.collection.collection-extensions.kt Maven / Gradle / Ivy
package run.smt.ktest.util.collection
fun Iterable.head() = this.first()
fun Iterable.headOption() = this.firstOrNull()
fun Iterable.tail() = this.drop(1)
fun Iterable.init() = this.reversed().tail().reversed()
fun Sequence.head() = this.first()
fun Sequence.headOption() = this.firstOrNull()
fun Sequence.tail() = this.drop(1)
fun Iterable.scan(start: R, accFunc: (R, T) -> R): List = fold(listOf(start)) { acc, newItem ->
acc + (accFunc(acc.last(), newItem))
}
fun Sequence.scan(start: R, accFunc: (R, T) -> R): Sequence = fold(sequenceOf(start)) { acc, newItem ->
acc + (accFunc(acc.last(), newItem))
}
fun Collection.padTo(newSize: Int): Collection {
return padTo(newSize, null)
}
fun Collection.padTo(newSize: Int, e: T): Collection {
return if (size < newSize) {
this + (0..(newSize - size)).map { e }
} else {
this
}
}
fun Sequence.zipWithIndex(): Sequence> = mapIndexed { i, v -> i to v }
fun Iterable.zipWithIndex(): Iterable> = mapIndexed { i, v -> i to v }
fun Sequence.permutations(): Sequence> {
headOption() ?: return emptySequence()
val tail = tail()
tail.headOption() ?: return sequenceOf(this)
return fold(emptySequence>()) { xs, x ->
xs + filterNot { it == x }.permutations().map { sequenceOf(x) + it }.asSequence()
}
}
fun Sequence.crossProduct(that: Sequence): Sequence> {
return flatMap { l ->
that.map { r ->
l to r
}
}
}
fun Sequence.partitionBy(selector: (T) -> Boolean): Pair, Sequence> {
return filter(selector) to filter(selector.negate())
}
inline fun Iterable.partitionBy(selector: (T) -> Boolean): Pair, Iterable> {
return filter(selector) to filter(selector.negate())
}
@Suppress("NOTHING_TO_INLINE")
inline fun ((T) -> Boolean).negate(): (T) -> Boolean = { !this(it) }