Suppose I have a data list val data = listOf("F 1", "D 2", "U 1", "D 3", "F 10") and I wanna perform the given logic on each element.
I have to add var acc2 = 0 outside to do this. I wonder is there any possible to get two accumulators in fold / reduce that this method be without side effect.
val data = listOf("F 1", "D 2", "U 1", "D 3", "F 10")
var acc2 = 0
val result = data.fold(0, { acc, str ->
when (str.split(" ")[0]) {
"F" -> {
acc + str.split(" ")[1].toInt() * acc2
}
"D" -> {
acc2 += str.split(" ")[1].toInt()
acc
}
"U" -> {
acc2 -= str.split(" ")[1].toInt()
acc
}
else -> {
acc
}
}
})