scoop:scoop.std:0.1.0
src/collections/transforms.scoop
Selected production source · src/collections/transforms.scoop
1
package scoop.collections3
/**4
* Transforms each element into a new list in iteration order.5
*/6
public fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> {7
val result = ArrayList<R>()8
for (element in this) result.add(transform(element))9
return ListSnapshot<R>(result.toArray())10
}12
/**13
* Transforms each element with its zero-based Long index into a new list.14
*/15
public fun <T, R> Iterable<T>.mapIndexed(transform: (Long, T) -> R): List<R> {16
val result = ArrayList<R>()17
var index = 0L18
for (element in this) {19
result.add(transform(index, element))20
index = nextCollectionCount(index)21
}22
return ListSnapshot<R>(result.toArray())23
}25
/**26
* Transforms each element, retaining and unwrapping only Some results in a new list.27
*/28
public fun <T, R> Iterable<T>.mapNotNone(transform: (T) -> R?): List<R> {29
val result = ArrayList<R>()30
for (element in this) {31
when (transform(element)) {32
case Some(val value) -> result.add(value)33
case None -> continue34
}35
}36
return ListSnapshot<R>(result.toArray())37
}39
/**40
* Copies elements satisfying the predicate into a new list in iteration order.41
*/42
public fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {43
val result = ArrayList<T>()44
for (element in this) { if (predicate(element)) result.add(element) }45
return ListSnapshot<T>(result.toArray())46
}48
/**49
* Copies elements failing the predicate into a new list in iteration order.50
*/51
public fun <T> Iterable<T>.filterNot(predicate: (T) -> Boolean): List<T> =52
filter<T> { element -> !predicate(element) }54
/**55
* Copies and unwraps Some elements into a new list, skipping None.56
*/57
public fun <T> Iterable<T?>.filterNotNone(): List<T> = mapNotNone<T?, T> { element -> element }59
/**60
* Concatenates each transformed iterable into a new list in source order.61
*/62
public fun <T, R> Iterable<T>.flatMap(transform: (T) -> Iterable<R>): List<R> {63
val result = ArrayList<R>()64
for (element in this) {65
for (value in transform(element)) result.add(value)66
}67
return ListSnapshot<R>(result.toArray())68
}70
/**71
* Concatenates the nested iterables into a new list in outer and inner iteration order.72
*/73
public fun <T> Iterable<Iterable<T>>.flatten(): List<T> = flatMap<Iterable<T>, T> { element -> element }75
/**76
* Returns two lists: matching elements first and nonmatching elements second, each retaining77
* source order.78
*/79
public fun <T> Iterable<T>.partition(predicate: (T) -> Boolean): (List<T>, List<T>) {80
val matches = ArrayList<T>()81
val others = ArrayList<T>()82
for (element in this) {83
if (predicate(element)) matches.add(element) else others.add(element)84
}85
val yes: List<T> = ListSnapshot<T>(matches.toArray())86
val no: List<T> = ListSnapshot<T>(others.toArray())87
return (yes, no)88
}