Scoop API

scoop:scoop.std:0.1.0

src/collections/transforms.scoop

Selected production source · src/collections/transforms.scoop

1package scoop.collections
3/**
4 * Transforms each element into a new list in iteration order.
5 */
6public 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())
12/**
13 * Transforms each element with its zero-based Long index into a new list.
14 */
15public fun <T, R> Iterable<T>.mapIndexed(transform: (Long, T) -> R): List<R> {
16 val result = ArrayList<R>()
17 var index = 0L
18 for (element in this) {
19 result.add(transform(index, element))
20 index = nextCollectionCount(index)
21 }
22 return ListSnapshot<R>(result.toArray())
25/**
26 * Transforms each element, retaining and unwrapping only Some results in a new list.
27 */
28public 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 -> continue
34 }
35 }
36 return ListSnapshot<R>(result.toArray())
39/**
40 * Copies elements satisfying the predicate into a new list in iteration order.
41 */
42public 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())
48/**
49 * Copies elements failing the predicate into a new list in iteration order.
50 */
51public 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 */
57public 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 */
62public 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())
70/**
71 * Concatenates the nested iterables into a new list in outer and inner iteration order.
72 */
73public 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 retaining
77 * source order.
78 */
79public 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)