Greg Stepniewski
07/31/2019, 8:06 PMfun Example.sequence(vararg operations: Example.() -> Example): List<Example> {
val sequence = mutableListOf(this)
operations.forEach { sequence.add(it(sequence.last())) }
return sequence.toList()
}
Shawn
07/31/2019, 8:08 PMfoldWithNext
Greg Stepniewski
07/31/2019, 8:14 PM5.sequence({plus(1)}, {minus(2)}, {times(2)}) // [5, 6, 4, 8]
Shawn
07/31/2019, 8:18 PMkarelpeeters
07/31/2019, 8:23 PMfun <T> T.chainOperations(ops: List<(T) -> T>): List<T> {
var curr = this
return listOf(curr) + ops.map { it(curr).also { curr = it } }
}
Dominaezzz
07/31/2019, 8:25 PMsequence {
var curr = this
for (op in operation) {
yield(curr)
curr = op(curr)
}
yield(curr)
}.toList()
Matias Reparaz
07/31/2019, 8:27 PMfun Example.sequence(vararg operations: Example.() -> Example): List<Example> {
return operations.fold(listOf(this)) {acc, cur -> acc + (cur(acc.last()))}
}
karelpeeters
07/31/2019, 8:28 PMfold
is called scan
in other languages.Greg Stepniewski
07/31/2019, 8:30 PMMatias Reparaz
07/31/2019, 8:37 PMDominaezzz
07/31/2019, 8:39 PMoperations.fold(mutableListOf(this)) { acc, cur -> acc += cur(acc.last()) }
might perform a bit better.karelpeeters
07/31/2019, 8:40 PMDominaezzz
07/31/2019, 8:40 PMmarstran
08/01/2019, 8:05 AMfun Example.sequence(vararg operations: Example.() -> Example): List<Example> {
if (operations.isEmpty()) {
return listOf(this)
}
val mappedExample = operations.first()(this)
val nextOperations = operations.drop(1)
val seq = mappedExample.sequence(*nextOperations.toTypedArray())
return listOf(this) + seq
}
It could probably be optimized to not create so many intermediate arrays and lists though. It should also probably be made tail recursive.karelpeeters
08/01/2019, 9:21 AMsubList(1)
instead of drop(1)
. Still terrible performance of course 🙃Dico
08/01/2019, 6:25 PMtailrec fun <E> E.sequence(ops: List<(E) -> E>, target: MutableList<E> = arrayListOf(), ind: Int = 0): List<E> {
target += this
if (ind >= ops.size) return target
return ops[ind](this).sequence(ops, target, ind+1)
karelpeeters
08/01/2019, 6:28 PMDico
08/01/2019, 6:29 PMkarelpeeters
08/01/2019, 6:29 PM