AdalPari
12/12/2019, 2:49 PM(1..9).fold("a", { last, current -> last + current })
This just returns a123456789 but I actually need to create the following list: { "a1", "a12", "a123", "a1234", .. }
I would be more like a map but knowing previous element:
(1..9).map { "$previousElement$it" }
streetsofboston
12/12/2019, 2:52 PMscan
? (this fun exists on Rx)AdalPari
12/12/2019, 2:54 PMKroppeb
12/12/2019, 3:47 PMHampus Londögård
12/12/2019, 4:15 PMwindowed
.
(1..9).windowed(size=2).map { items -> "${items.first()}${items.last()}" }
It defaults to partialWindows=false
. Not really what you asked for though, but it does the job 🙂Kroppeb
12/12/2019, 4:17 PMHampus Londögård
12/12/2019, 4:17 PMKroppeb
12/12/2019, 4:20 PMvar previous = "a"
(1..9).map {current ->
previous += current
previous
})
Hampus Londögård
12/12/2019, 4:22 PM(1..9).fold(listOf<String>()) { acc, current -> acc + ((acc.lastOrNull() ?: "") + current) }
streetsofboston
12/12/2019, 4:22 PMKroppeb
12/12/2019, 4:26 PMscan
implementation I have in my utils for AoC. It doesn't return the start value. If you want the start value to also be returned you can change line 3 to val ret = mutableListOf(start)
streetsofboston
12/12/2019, 4:52 PMscan
, which can handle large collections and scans the in- and out-put values one at a time, avoiding the allocation of possibly large collections until the end.
fun <T, R> Sequence<T>.scan(start: R, oper: (R, T) -> R): Sequence<R> = sequence {
var next = start
for (value in iterator()) {
next = oper(next, value).also { yield(it) }
}
}
fun <T, R> Iterable<T>.scan(start: R, oper: (R, T) -> R): Iterable<R> =
this.asSequence().scan(start, oper).asIterable()
It uses a Sequence
to do so.AdalPari
12/12/2019, 5:05 PM